import { ModalMultipleSelect3FullScreenComponent } from './../modal-multiple-select3-full-screen/modal-multiple-select3-full-screen.component';
// tslint:disable
import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { ModalOfLocalEditComponent } from './../modal-of-local-edit/modal-of-local-edit.component';
// import { TabsService } from 'src/app/shared/service/tabs.service';
import { Component, ElementRef, Input, OnInit, Renderer2, ViewChild, OnDestroy, ChangeDetectorRef } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

import { ModalController, PickerController, NavParams, AlertController, Platform } from '@ionic/angular';
import { ActionSheetService, zh_CN } from 'ng-zorro-antd-mobile';
import { ModalOfMultipleComponent } from '../modal-of-multiple/modal-of-multiple.component';
import { ModalOfPersonSelectComponent } from '../modal-of-person-select/modal-of-person-select.component';
import { ModalOfSelectComponent } from './../modal-of-select/modal-of-select.component';
import { ChooseCityComponent } from './../../choose-city/choose-city.component';
import { RecommendModalComponent } from './../../recommend-modal/recommend-modal.component';
import { ShowMapPage } from './../../address/show-map/show-map.page';
import { AppGlobalService } from '../../../shared/service/app-global.service';
import { HttpService } from './../../../shared/service/http.service';
import { MapBaiduService } from './../../../shared/service/map.baiduapi';
import { PublishHouseTypeComponent } from '../../publish-house-type/publish-house-type.component';
import { ChooseDepartmentComponent } from '../../choose-department/choose-department.component';
import { isNullOrUndefined } from 'util';
import { ServiceTypeComponent } from '../../service-type/service-type.component';
import { ModalMultipleSelect3Component } from '../modal-multiple-select3/modal-multiple-select3.component';
import { toUnicode } from 'punycode';
import { Contacts } from '@ionic-native/contacts';
import { EventService } from 'src/app/shared/service/event.service';
import { ModalFromCenterEnter, ModalFromCenterLeave, ModalFromRightEnter, ModalFromRightLeave } from 'src/app/utils/transitions';
import { UploadImageService } from 'src/app/shared/service/uploadImageService';
import AddressParse from 'address-parse';
import { FwPickerComponent } from '../fw-picker/fw-picker.component';
declare var BMap;
declare let $: any;
declare let Quill: any;
declare let Keyboard: any;
@Component({
  selector: 'app-modal-of-edit-more-info',
  templateUrl: './modal-of-edit-more-info.component.html',
  styleUrls: ['./modal-of-edit-more-info.component.scss'],
})
export class ModalOfEditMoreInfoComponent implements OnInit, OnDestroy {
  constructor(
    private appGlobalService: AppGlobalService,
    private picker: PickerController,
    private modalCtrl: ModalController,
    private http: HttpService,
    private alertController: AlertController,
    private mapBaiduSerivce: MapBaiduService,
    private pageModalService: PageModalService,
    private uploadImageService: UploadImageService,
    private eventService: EventService,
    private contacts: Contacts,
    private renderer2: Renderer2,
    private element: ElementRef,
    private cd: ChangeDetectorRef,
    private platform: Platform,
    public navParams: NavParams) {
  }

  tagData: any;
  tagDataTemp: any;
  showCheckAll: any; // 三级选 是否包含全选
  title: any;
  sureBtnTitle: any;
  dataType = 0; // 小区：0 账号选择： 1 邀请者： 2
  formGroup: FormGroup;
  allLabel: any = {};
  minTime: any = '1990';
  time = -1;
  pageCity: any;
  pageCityCode: any;
  addressValue: any;
  positionInfo: any;
  address: any = {};
  isNextStep: any;
  showSureBtn = true;
  hasNextStep = false; // 还有下一步
  showSearchModal: any; // 1:search 2: add
  submitBtnData: any;
  allForm: FormGroup; // 上一个页面完整的form
  transparent = false; // header 是否透明
  // time
  locale = zh_CN;
  compareItemArray: any = [];
  houseTypeShowValue = '';
  // search
  keyword = '';   // 搜索关键词
  hasSearched: Boolean = false;     // 是否已经搜索
  searchArr: any[];       // 搜索历史记录数组
  sarchData: any;        // 搜索结果数据
  searchType: any;
  focus: any;
  bigDistrict: any;
  timer: any;
  timer1: any;
  navBtnList: any; // 导航栏增加btn
  btnList: any; // 修改发布btn文案
  todayHHMM: any; //今天的时和分
  min: any; // 分钟
  labelCssStyle: any;
  textInputJoinArray = []; // 
  @Input() newAdd: any;
  @Input() editItem: any;
  @Input() cssClass: any;
  @ViewChild('searchBar') searchBar;
  @ViewChild('fwInput') fwInputM;
  @ViewChild('searchBarLocal') searchBarLocal;
  appTypeCustom: any;
  nextPageFomObj: any; // 下一步
  hintId = 'hintId';
  lastClickImaga = 0;
  quill: any;
  modalId: any;
  titleCssStyle:any;
  ngAfterViewInit() {
    this.timer1 = setInterval(() => {
      try {
        // 修改 ion-range 样式
        const ionBackButton = this.element.nativeElement.querySelector('ion-range'); if (ionBackButton) {
          const styleSheet = `
      .range-bar{
        width:calc(100% + 5vw - 0.15rem) !important
      }
      .range-bar.range-bar-active {
        left: calc(-6vw + 0.15rem) !important;
        width:auto !important;
      }
      `;
          this.appGlobalService.injectStyleToShadowRoot(this.renderer2, ionBackButton, styleSheet);
        }
      } catch (error) {

      }

    }, 50);

    this.timer = setInterval(() => {
      try {
        let n = 0;
        this.textInputJoinArray.forEach(element => {
          var x = document.getElementById(element.formKey)
          if (x && element.changedCss !== true) {
            element.changedCss = true;
            x.setAttribute("style", element.valueCssStyle);
          }
          if (element.changedCss === true) {
            ++n;
          }
        });
        if (n === this.textInputJoinArray.length) {
          clearInterval(this.timer);
        }


      } catch (error) {

      }

    }, 50);
  }

  ngOnInit() {
    this.hintId += new Date().getTime();
    const bodyStyles = window.getComputedStyle(document.body);
    this.appTypeCustom = bodyStyles.getPropertyValue('--appTypeCustom').trim().replace('"', '').replace('"', '');
    this.addressValue = {};
    this.positionInfo = JSON.parse(localStorage.getItem('position'));
    console.log(this.positionInfo, 'this.positionInfo');
    this.minTime = this.appGlobalService.getNowFormatDateYYYYMMDD();
    this.todayHHMM = this.appGlobalService.getNowFormatDateHHMM()
    console.log(this.minTime, this.todayHHMM);
    // 模态编辑更多信息
    this.tagDataTemp = this.navParams.data.value.subHtmlObj ? this.navParams.data.value.subHtmlObj : this.navParams.data.value;
    this.tagData = JSON.parse(JSON.stringify(this.tagDataTemp));
    if(this.navParams.data.value.placeholderCssStyle){
      this.titleCssStyle = this.navParams.data.value.placeholderCssStyle;
    }
    if(this.navParams.data.value.useLabelCssAsTitleCss && this.navParams.data.value.labelCssStyle){
      this.titleCssStyle = this.navParams.data.value.labelCssStyle;
    }
    if(this.navParams.data.value.placeHolder && this.navParams.data.value.usePlaceHolderAsTitle) {
      this.title = this.navParams.data.value.placeHolder;
    } else {
      this.title = this.navParams.data.value.label;      
    }
    
    
    if (this.navParams.data.value.labelCssStyle) {
      this.labelCssStyle = this.navParams.data.value.labelCssStyle;
    }
    this.showCheckAll = this.navParams.data.value.checkAll;
    if (this.navParams.data.value.showLabel == false) {
      this.title = '';
    }
    if (!this.navParams.data.value.showSureBtn) {
      this.showSureBtn = this.navParams.data.value.showSureBtn;
    }

    this.isNextStep = this.navParams.data.nextStep;
    this.showSearchModal = this.navParams.data.showSearchModal;
    this.formGroup = new FormGroup({});
    if (this.isNextStep) {
      this.title = this.navParams.data.value.tips;
      this.submitBtnData = this.appGlobalService.globalSubmitBtnData;
      this.appGlobalService.globalHiddenForm = this.formGroup;
      this.appGlobalService.globalHiddenMessageObj = this.allLabel;
      this.allForm = this.navParams.data.allForm;
    }
    if (this.eventService.eventEmit.listenerCount('nextPageFomObj') > 0) {
      this.eventService.eventEmit.removeListener('nextPageFomObj');
    }
    if (this.navParams.data.value.formType === 'nextPageFomObj') {
      if (this.navParams.data.value.value && this.navParams.data.value.value.length > 0) {
        this.transparent = true;
      } else {
        this.transparent = false;
      }
      if (this.navParams.data.value.itemList) {
        this.navParams.data.value.itemList.forEach(element => {
          if (element.value === 'navBtn') {
            if (!this.navBtnList) {
              this.navBtnList = [];
              this.navBtnList.push(element);
            } else {
              this.navBtnList.push(element);
            }
          } else if (element.value === 'submitText') {
            if (!this.btnList) {
              this.btnList = [];
              this.btnList.push(element.label);
            } else {
              this.btnList.push(element.label);
            }

          }
        });
        if (this.btnList) {
          this.eventService.eventEmit.emit("changeBtnTitle", JSON.stringify(this.btnList));
        }
      }
    }

    this.buildForm();
    if (this.newAdd === true) {
      // this.formGroup.reset();
    } else if (this.newAdd === false) {
    }
    if (this.showSearchModal === 1) {
      if (this.title.indexOf('小区') > -1) {

        if (this.navParams.data.value.hasAddNew !== false) {
          this.sureBtnTitle = '添加小区';
        } else {
          this.sureBtnTitle = '';
        }
        this.dataType = 0;
        this.searchType = "searchTypeXQ";
      } else if (this.title.indexOf('账号') > -1) {
        this.sureBtnTitle = '新增账号';
        this.dataType = 1;
        this.searchType = "searchTypeZH";
      } else if (this.title.indexOf('人') > -1 ||
       this.title.indexOf('协助') > -1 || 
       this.title.indexOf('邀请') > -1 || 
       this.title.indexOf('发布') > -1 ||
       this.title.indexOf('管家') > -1 ||
        this.title.indexOf('签约') > -1) {
        this.sureBtnTitle = '';
        this.dataType = 2;
        this.searchType = "searchTypeYQ";
      } else {
        this.sureBtnTitle = '';
      }

      console.log("search type ---->", this.searchType);
      this.searchArr = JSON.parse(localStorage.getItem(this.searchType))
        ? JSON.parse(localStorage.getItem(this.searchType))
        : [];
    } else if (this.showSearchModal === 2) {
      if (this.title.indexOf('小区') > -1) {
        this.title = '添加小区';
        this.dataType = 0;
      } else if (this.title.indexOf('账号') > -1) {
        this.title = '新增账号';
        this.dataType = 1;
      } else if (this.title.indexOf('邀请') > -1) {
        this.title = '选择新邀请者';
        this.dataType = 2;
      } else {
        this.title = '';
      }

    }
  
  }

  initRichTextEdit(formItem) {
    const that = this;
    setTimeout(() => {
      if (document.getElementById("id-rich-text-" + formItem.formKey + that.hintId)) {
        if ((typeof Keyboard) !== 'undefined' && localStorage.getItem('client') === 'APP') {
          // Keyboard.disableScroll(false);
          // Keyboard.setResizeMode('none');
          console.log('iOS:Keyboard.Scroll!!!!' );
        }
        //  421 8421
        let  toolbarOptions = [];
          if (formItem.maxSize > 0) {
            if (formItem.maxSize & 0x01){
              toolbarOptions.push([{ header: [false, 1, 2, 3, 4] }]);
            }
            if (formItem.maxSize & 0x02){
              toolbarOptions.push([{ size: ['12', false, "16", "18", '22', "26"] }]);
            }
            if (formItem.maxSize & 0x04){
              toolbarOptions.push(['bold']);
            }
            if (formItem.maxSize & 0x08){
              toolbarOptions.push([{ color: [] }]);
            }
            if (formItem.maxSize & 0x10){
              toolbarOptions.push([{ align: [] }]);
            }
            if (formItem.maxSize & 0x20){
              toolbarOptions.push([{ list: 'ordered'}], [{ list: 'bullet' }]);
            }
            if (formItem.maxSize & 0x40){
              toolbarOptions.push(['image']);
            }
          } else {
            toolbarOptions = [
              [{ header: [false, 1, 2, 3, 4] }], // 1
              [{ size: ['12', false, "16", "18", '22', "26"] }], // 2
              ['bold'], // 4
              [{ color: [] }],// 8
              [{ align: [] }], // 1
              [{ list: 'ordered'}], [{ list: 'bullet' }],// 2
              ['image'] // 4
              ];
          }
          that.quill = new Quill("#id-rich-text-" + formItem.formKey + that.hintId , {
          modules: {
            toolbar: toolbarOptions,
            // history: {
            //   delay: 2000,
            //   maxStack: 100,
            //   userOnly: true
            // }
          },
          theme: 'snow',
          placeholder: formItem.placeHolder ? formItem.placeHolder :( formItem.extra ? "" : '请输入内容详情'),
  
        });
        
        const targetE = document.querySelector('.ql-toolbar') as Element
        const element = document.getElementById("header-"+ that.hintId).appendChild(targetE);
    
        if (formItem.value && formItem.value.length > 0) {
          that.quill.pasteHTML(formItem.value);
          formItem.showValue = '已填写';  
        } else {
          that.quill.pasteHTML('');
          formItem.showValue = '';
        }
        if (formItem.cropperRatio && formItem.cropperRatio > 0) {
          that.quill["cropperRatio"]  =  formItem.cropperRatio;
        } else {
          that.quill["cropperRatio"]  =  0;
        }
        
        // 获取quill的工具栏对象
        const toolbar = that.quill.getModule('toolbar');
        // 给工具栏的image功能添加自定义函数，注意this指向问题
        toolbar.addHandler('image', that.imageHandler.bind(this)); 
        that.quill.on('editor-change', function(eventName, ...args) {
          if (eventName === 'text-change') {
            // args[0] will be delta
            
            let value = that.quill.container.firstChild.innerHTML;
            if (value === '<p><br></p>' || value === '<p> </p>') {
              value = "";
              formItem.showValue = '';
            } else {
              formItem.showValue = '已填写';  
            }
            formItem.value = value;
            // console.log('content===',  value);
            that.formGroup.patchValue({ [formItem.formKey]: value});
            
          } else if (eventName === 'selection-change') {
            // args[0] will be old range
            if (args[1] && args[1].length  > 0) {
              
              if (!that.quill.hasFocus()) {
                that.quill.focus();
                console.log('set focus');  
              } 
            } else {
              
              console.log('selection-change none');
            }
          }
  
        });
      }
      
    }, 500);
  }


   // 自定义图片上传功能
  // 创建一个input对象来实现上传，除了下面的自定义代码区域，其他为官方代码
  imageHandler() {
    const now =  new Date().getTime();
    // console.log('now' + (now));
    if (now - this.lastClickImaga <= 100) {
      // console.log('间隔：' + (now - this.lastClickImaga));
      this.lastClickImaga = now;
      return;
    }
    this.lastClickImaga = now;
    const that = this;
    const cropperRatio = that.quill["cropperRatio"]; // W/H 2.54
    if (this.platform.is('cordova')) {
       /* 自定义代码 */
       that.uploadImageService.presentAction(imageUrl=>{
        // 必要的，成功后执行 （imageUrl 为上传成功后的图片完整路径）
        that.quill.insertEmbed(that.quill.getSelection(true).index, 'image', imageUrl);
      },cropperRatio);

      if ((typeof Keyboard) !== 'undefined' &&
        localStorage.getItem('client') === 'APP') {
          Keyboard.hide();
          
          console.log('Keyboard.Hide!!!!');
        }
    } else {
      
      const Imageinput = document.createElement('input');
      Imageinput.setAttribute('type', 'file');
      Imageinput.setAttribute('accept', 'image/png, image/gif, image/jpeg, image/bmp'); // 可改上传图片格式
      Imageinput.classList.add('ql-image');
      Imageinput.addEventListener('change', () => {
        const file = Imageinput.files[0];
        if (Imageinput.files != null && Imageinput.files[0] != null) {
            /* 自定义代码 */
            that.uploadImageService.uploadFileForWeb(file, imageUrl=>{
              // 必要的，成功后执行 （imageUrl 为上传成功后的图片完整路径）
              that.quill.insertEmbed(that.quill.getSelection(true).index, 'image', imageUrl);
            },cropperRatio)
            
        }
      }); 
      Imageinput.click();
    }
    
    
  }
  // 添加表单控件
  buildForm(): void {
    if (this.tagData.length) {
      for (let i = 0; i < this.tagData.length; i++) {
        const formItem = this.tagData[i];
        if (formItem.formType === 'nextPageFomObj') {
          this.hasNextStep = true;
          this.nextPageFomObj = formItem;
          break;
        } else {
          this.addFormCtrl(formItem);
        }
      }
    } else {
      this.addFormCtrl(this.tagData);
    }
  }

  // 存储需要的对比的项目
  compareMinAndMaxValue(item) {
    if (item.compare && item.subHtmlObj && item.subHtmlObj.length === 2) {
      const compareItem = {
        label: item.label,
        lessTip: '',
        equalTip: '',
        canEqual: item.canEqual,
        minKey: item.subHtmlObj[0].formKey,
        maxKey: item.subHtmlObj[1].formKey
      };
      if (item.lessTip && item.lessTip.length > 0) {
        compareItem.lessTip = item.lessTip;
      }
      if (item.equalTip && item.equalTip.length > 0) {
        compareItem.equalTip = item.equalTip;
      }
      this.compareItemArray.push(compareItem);
    }
  }
  addFormCtrl(formItem) {
    const that = this;
    if (formItem.formType === 'nextPageFomObj') {
      this.nextPageFomObj = formItem;
      // this.cd.detectChanges();
      return;
    }
    if (formItem.formKey && formItem.formKey.length > 0) {

      this.addFormControl(formItem);
    }
    if (formItem.subHtmlObj && formItem.subHtmlObj.length > 0 && formItem.formType !== 'modalOfLocalEdit' && formItem.formType !== 'modalOfMoreItems') {
      formItem.subHtmlObj.forEach((element, i) => {
        // 第三层组合为第二层的formKey value
        if ((!element.formKey || element.formKey === '') && element.formType !== 'modalOfMoreItems') {
          element.formKey = 'cus_' + formItem.formKey + i;
          element.value = '';
          // 赋值
          if (formItem.value && formItem.value !== '') {
            const arr = formItem.value.split(',');
            element.value = arr[i] ? arr[i] : '';
          }
        }
        if (!element.showCondition || (element.showCondition && element.showCondition.indexOf(formItem.value) > -1)) {
          that.addFormCtrl(element);
        }
      });
    }
  }

  addFormControl(formItem) {

    const that = this;
    if (formItem.formKey && formItem.formKey.length > 1 && !this.formGroup.controls[formItem.formKey]) {
      if (formItem.formType === 'multipleColumnSelect' || formItem.formType === 'multipleColumnSelectLJ') {
        if (formItem.value && formItem.value.length) {
          if (Array.isArray(formItem.value)) {
          } else {
            formItem.value = formItem.value.split(",");
          }
        }
      }
      else if(formItem.formType === 'datePicker' ||
      formItem.formType === 'datePlug' ||
      formItem.formType === 'ionDatetime' ||
      formItem.formType === 'datePickerLJ') {
        if (!formItem.value || formItem.value === '') {
          formItem.valueN =  formItem.placeHolder ? formItem.placeHolder : formItem.label;
        } else {
          formItem.valueN = formItem.showValue ? formItem.value + ' ' + ' ' + formItem.showValue : formItem.value;
        }
      }
      if (this.formGroup.contains(formItem.formKey)) {
        this.formGroup.patchValue({ [formItem.formKey]: formItem.value });
      } else {
        this.formGroup.addControl(formItem.formKey, new FormControl(formItem.value, that.validators(formItem)));
      }
    }

    // 上次坐标
    if (formItem.formType === 'detailAddress_location') {
      if (this.addressValue && this.addressValue.location) {
        formItem.value = this.addressValue.location;
        this.formGroup.patchValue({ [formItem.formKey]: formItem.value });
      }
    }

    if (formItem.rules && formItem.rules.length > 0) {
      const message: any = {};
      formItem.rules.forEach(rule => {
        // 将key 转小写
        message[rule.name.toLowerCase()] = rule.message;
      });
      message.label = formItem.label;
      this.allLabel[formItem.formKey] = message;
    }
    // 设置样式
    if (formItem && (formItem.formType === 'textInputJoin' || formItem.formType === 'textAreaLJ') && formItem.valueCssStyle) {
      this.textInputJoinArray.push(formItem)
    }
    if (formItem.formType === 'showSingleSelect') {
      if (formItem.data && formItem.data.length > 0) {
        formItem.itemList = formItem.data;
      }
    }
    if (formItem.formType === 'richTextEdit') {
     this.initRichTextEdit(formItem);
    } else if (formItem.formType === 'updateRules') {
      if (formItem.value && formItem.value === '1' || formItem.value === 1) {
        formItem.checked = true;
      } else {
        formItem.checked = false;
        formItem.value = '';
      }
      this.formGroup.patchValue({ [formItem.formKey]: formItem.value });
     } else
    // 设置初始值
    if (formItem.formType === 'switchButton' ||
      formItem.formType === 'switchButtonLJ' ||
      formItem.formType === 'switchButtonLJ_icon' ||
      formItem.formType === 'switchButtonFW' ||
      formItem.formType === 'switchButtonFW_3' ||
      formItem.formType === 'radioButton' ||
      formItem.formType === 'switchButtonJoin' ||
      formItem.formType === 'chooseGrade' ||
      formItem.formType === 'showSingleSelect' ) {
      if (formItem.itemList) {
        if (formItem.multiSelect === true || formItem.multiSelect === "true") {
          const valueArray: any = [];
          let value = '';
          if (formItem.value){
            let array = [];
            if (formItem.sep !== undefined) {
              array = formItem.value.split(formItem.sep)
            } else {
              array = formItem.value.split(';')
            }            formItem.itemList.forEach(e => {
              array.forEach(a => {
                if (a === e.value) {
                  e.check = true;
                }  
              });
              
            });

          } else {
            formItem.itemList.forEach(e => {
              if (e.check) {
                valueArray.push(e.value);
              }
            });
          }
          
          if (formItem.formType === 'showSingleSelect') {
            value = valueArray.join(',');
          } else {
            value = valueArray.join(';');
          }
          if (formItem.sep !== undefined) {
            value = valueArray.join(formItem.sep);
          }
          formItem.value = value;
          this.formGroup.patchValue({ [formItem.formKey]: formItem.value });

        } else {
          // tslint:disable-next-line:no-shadowed-variable
          formItem.itemList.forEach(element => {
            if (element.check) {
              formItem.value = element.value;
              formItem.showValue = element.label;
              that.formGroup.patchValue({ [formItem.formKey]: formItem.value });
            }
          });
        }
      }

    } else if (formItem.formType === 'switchButtonSystem') {
      formItem.showValue = formItem.value === '1' ? true : false;
      this.formGroup.patchValue({ [formItem.formKey]: formItem.value });

    } else if (formItem.formType === 'singleColumnSelectLJ' || formItem.formType === 'singleColumnSelect') {

      if (formItem.subHtmlObj && formItem.subHtmlObj.length > 0) {
        formItem.subHtmlObj.forEach(it => {
          if ((formItem.value && it.showCondition && (it.showCondition.indexOf(formItem.value) > -1 || formItem.value.indexOf(it.showCondition) > -1)) || !it.showCondition) {

            if ((it.formType === 'modalMultipleSelectLJ_AfterSubmit' || it.formType === 'modalMultipleSelect3_Full' || it.formType === 'modalMultipleSelect3_Full_Common' || it.formType === 'modalMultipleSelect3_Auto_Full') && it.submit) {

              it.submit.content = { [formItem.formKey]: formItem.value }
              if (it.formType === 'modalMultipleSelect3_Full' || it.formType === 'modalMultipleSelect3_Auto_Full' || it.formType === 'modalMultipleSelect3_Full_Common') {
                it.children = [];
              } else {
                it.data = [];
              }

              // 清空一下
              // this.formGroup.patchValue({ [it.formKey]: '' });
              // it.value = '';
              // it.showValue = '';
              this.getIndustryData(it);

            }
          }
        });
      }

    } else if (formItem.formType === 'modalMultipleSelect' || formItem.formType === 'modalMultipleSelectLJ' || formItem.formType === 'multipleSelectLJ') {
      if (!(formItem.showValue && formItem.showValue.length > 0)) {
        formItem.showValue = formItem.placeHolder;
      }
      if (formItem.submit && (formItem.data === undefined || formItem.data.length === 0)) {
        formItem.data = [];
        this.getIndustryData(formItem);
      }
    } else if (formItem.formType === 'pickerSelect' || formItem.formType === 'pickerSelectLJ' || formItem.formType === 'pickerSelectDesign' || formItem.formType === 'pickerSelectJoin' || formItem.formType === 'pickerSelectTwoLine') {
      if (!(formItem.showValue && formItem.showValue.length > 0)) {
        formItem.showValue = formItem.placeHolder;
      }

      if (formItem.submit) {
        formItem.data = [];
        this.getIndustryData(formItem);
      }
    } else if (formItem.formType === 'datePicker' || formItem.formType === 'datePickerLJ' || formItem.formType === 'datePlug') {
      // 增加默认值
      if (formItem.defValue) {
        formItem.defValue = this.getDateTime(formItem.defValue);
      } else {
        // formItem.defValue = !formItem.value  ?  new Date() : this.getDateTime(formItem.value);
      }
    } else if (formItem.formType === 'mCitySelect') {

      this.getCityData(formItem);
    } else if (formItem.formType === 'citySelect' || formItem.formType === 'citySelectLJ') {
      if (!formItem.showValue || !formItem.showValue.length) {
        formItem.showValue = this.positionInfo.name;
        this.pageCity = this.positionInfo.name;
        this.pageCityCode = this.positionInfo.code;
        formItem.value = this.positionInfo.code;
      }
      // 获取上次区域的值
      if (formItem.subHtmlObj && formItem.subHtmlObj.length > 0 && formItem.subHtmlObj[0].showValue) {
        this.bigDistrict = formItem.subHtmlObj[0].showValue;
      }
      this.formGroup.patchValue({ [formItem.formKey]: formItem.value });
      this.getAreaData(formItem);
    } else if (formItem.formType === 'detailAddress_location') {
      if (formItem.value && formItem.value.indexOf(",")) {
        that.positionInfo.center.lng = formItem.value.split(",")[1];
        that.positionInfo.center.lat = formItem.value.split(",")[0];
      }
      if (this.addressValue && this.addressValue.location) {
        formItem.value = this.addressValue.location;
      }
    } else if (formItem.formType === 'selectAddressWidget' || formItem.formType === 'selectAddressWidgetLJ') {
      formItem.value = formItem.showValue ? formItem.showValue : "";
    } else if (formItem.formType === 'contractSelectWidget' || formItem.formType === 'contractSelectWidgetLJ') {

      if (formItem.value === 'true') {
        this.formGroup.patchValue({ [formItem.formKey]: "true" });
        formItem.subHtmlObj.forEach(element => {
          that.addFormControl(element);
        });

      } else {
        this.formGroup.patchValue({ [formItem.formKey]: "false" });
        formItem.subHtmlObj.forEach(element => {
          that.removeFormControl(element);
        });
      }
    } else if (formItem.formType === 'detailAddress' || formItem.formType === 'detailAddressLJ') {
      if (formItem.latitude && formItem.longitude) {
        that.positionInfo.center.lng = formItem.longitude;
        that.positionInfo.center.lat = formItem.latitude;
      }
      if (formItem.subHtmlObj && formItem.subHtmlObj[0].formType === 'detailAddress_location') {
        if (formItem.subHtmlObj[0].value && formItem.subHtmlObj[0].value.indexOf(",") > -1) {
          that.positionInfo.center.lng = formItem.subHtmlObj[0].value.split(",")[1];
          that.positionInfo.center.lat = formItem.subHtmlObj[0].value.split(",")[0];
        }
      }
    } else if (formItem.formType === 'modalMultipleFormKeySelect') {
      this.houseTypeShowValue = '';
      if (formItem.showValue !== undefined) {
        this.houseTypeShowValue = formItem.showValue;
        if (formItem.subHtmlObj[0] && formItem.subHtmlObj[0].value) {
          formItem.roomType = formItem.subHtmlObj[0].value;
          this.formGroup.patchValue({ [formItem.subHtmlObj[0].formKey]: formItem.subHtmlObj[0].value });
        }
        if (formItem.subHtmlObj[1] && formItem.subHtmlObj[1].value) {
          formItem.roomHall = formItem.subHtmlObj[1].value;
          this.formGroup.patchValue({ [formItem.subHtmlObj[1].formKey]: formItem.subHtmlObj[1].value });
        }
        if (formItem.subHtmlObj[2] && formItem.subHtmlObj[2].value) {
          formItem.roomBit = formItem.subHtmlObj[2].value;
          this.formGroup.patchValue({ [formItem.subHtmlObj[2].formKey]: formItem.subHtmlObj[2].value });
        }
      } else {
        if (formItem.subHtmlObj[0] && formItem.subHtmlObj[0].data) {
          this.houseTypeShowValue += formItem.subHtmlObj[0].data[0].label;
          formItem.roomType = formItem.subHtmlObj[0].data[0].value;
          this.formGroup.patchValue({ [formItem.subHtmlObj[0].formKey]: formItem.subHtmlObj[0].data[0].value });
        }
        if (formItem.subHtmlObj[1] && formItem.subHtmlObj[1].data.length > 0) {
          this.houseTypeShowValue += formItem.subHtmlObj[1].data[0].label;
          formItem.roomHall = formItem.subHtmlObj[1].data[0].value;
          this.formGroup.patchValue({ [formItem.subHtmlObj[1].formKey]: formItem.subHtmlObj[1].data[0].value });
        }
        if (formItem.subHtmlObj[2] && formItem.subHtmlObj[2].data.length > 0) {
          this.houseTypeShowValue += formItem.subHtmlObj[2].data[0].label;
          formItem.roomBit = formItem.subHtmlObj[2].data[0].value;
          this.formGroup.patchValue({ [formItem.subHtmlObj[2].formKey]: formItem.subHtmlObj[2].data[0].value });
        }
      }
    } else if (formItem.formType === 'modalOfLocalEdit') {
      formItem.showValue = (formItem.dataValue && formItem.dataValue.length > 0) ? '编辑' : '';
    } else if (formItem.formType === 'multipleSelect3' || formItem.formType === 'threeLevelSelection') {
      if (formItem.formType === 'threeLevelSelection'){

        if (formItem.children && formItem.children.length > 0) {
          this.initThreeLevelData(formItem);
        } else {
          if (formItem.submit && formItem.submit.content) {
            this.getCityData(formItem);
         }
        }
      } else{
        this.initThreeLevelData(formItem);
      }
      

    } else if (formItem.formType === 'multipleDesignStyleSelect') {
      if (formItem.itemList) {
        let arrayS = [];

        formItem.itemList.forEach(element => {
          if (element.status === 'true') {
            arrayS.push(element)
          }
        });
        formItem.itemList.forEach(element => {
          if (element.status !== 'true') {
            arrayS.push(element)
          }
        });
        formItem.itemList = arrayS;
      }


    }
    else if (formItem.formType === 'sectionDesc') {
      if (formItem.link && formItem.link.params && formItem.link.params.eventId) {
        let tempFormGrop = this.formGroup;
        this.eventService.eventEmit.on(formItem.link.params.eventId, (obj) => {
          console.log('obj===', obj);
          formItem.showValue = obj.text;
          formItem.value = obj.id;
          tempFormGrop.patchValue({ [formItem.formKey]: obj.id });
        });
      }
    }
    else if (formItem.formType === 'chooseTime') {

      formItem.daysList = [];
      formItem.itemList = [];

      this.createDate(formItem);
      this.createHour(formItem);
    }
    else if (formItem.formType === 'chooseTimeRange') {
      formItem.daysList = [];
      formItem.itemList = [];
      this.createDate(formItem);
      this.createHourRange(formItem);
    } else if (formItem.formType === 'showSingleSelect') {
      if (formItem.data && formItem.data.length > 0) {
        formItem.itemList = formItem.data;
      }
    } else if (formItem.formType === 'singleSelect3') {
      this.formGroup.patchValue({ [formItem.formKey]: formItem.value });

      if (formItem.children.length > 0) {
        formItem.children[0].open = true;
        formItem.current = formItem.children[0];
      }
    
      formItem.children.forEach(big => {
         {
          // 2
          big.children.forEach(m => {
            if (formItem.value === (m.value)){
              formItem.children[0].open = false;
              m.checked = true;
              big.open = true;
              formItem.current = big;
            }
            if (m.children && m.children.length > 0) {
              // 3
              m.children.forEach(s => {
                if (formItem.value === (s.value)){
                  formItem.children[0].open = false;
                  s.checked = true;
                  big.open = true;
                  formItem.current = big;
                }
              });
            }
          });
        }})

    } else if (formItem.formType === 'photoSelectWidget') {
      if (formItem.textType && formItem.textType === 'pdf') {
        if (formItem.formKeys && formItem.formKeys.indexOf(";")) {
          const keyArray = formItem.formKeys.split(";");
          if (this.formGroup.contains(keyArray[0])) {
            this.formGroup.patchValue({ [keyArray[0]]: formItem.valueLong});
            this.formGroup.patchValue({ [keyArray[1]]: formItem.valueIndex });
          } else {
            this.formGroup.addControl(keyArray[0], new FormControl(formItem.valueLong ));
            this.formGroup.addControl(keyArray[1], new FormControl(formItem.valueIndex ));
          }
        }
      }
    }
    
    this.compareMinAndMaxValue(formItem);
    this.checkSubHtmlObj(formItem);
  }
  removeFormControl(formItem) {
    const that = this;
    if (this.formGroup.controls[formItem.formKey]) {
      this.formGroup.removeControl(formItem.formKey);
      if (formItem.rules && formItem.rules.length > 0) {
        delete this.allLabel[formItem.formKey];
        this.appGlobalService.setFormGroupMessageWithParamName(this.tagData.paramName, this.allLabel);
      }
    }
    // formItem 没有formKey的情况也要遍历下级并清除
    if (formItem.subHtmlObj && formItem.subHtmlObj.length) {
      formItem.subHtmlObj.forEach(element => {
        that.removeFormControl(element);
      });
    }
  }


  // 上传身份信息控件      uploadIdentityWidget
  uploadIdentityWidgetControl(formItem) {
    const that = this;
    formItem.subHtmlObj.forEach(element => {
      that.addFormControl(element);
    });
  }

  // 数据校验
  validators(item) {
    const validators = [];
    if (item.rules && item.rules.length) {
      item.rules.forEach(rule => {
        if (rule.name === 'required' && rule.value === 'true') {
          validators.push(Validators.required);
        } else if (rule.name === 'minLength') {
          validators.push(Validators.minLength(Number(rule.value)));
        } else if (rule.name === 'maxLength') {
          validators.push(Validators.maxLength(Number(rule.value)));
        } else if (rule.name === 'min') {
          validators.push(Validators.min(Number(rule.value)));
        } else if (rule.name === 'max') {
          validators.push(Validators.max(Number(rule.value)));
        } else if (rule.name === 'pattern') {
          validators.push(Validators.pattern(rule.value));
        }
      });
    }
    return validators;
  }
  // 更新身份验证数据
  updateIdentityHandler(event) {
    this.formGroup.patchValue({ [event.formKey]: event.value });
  }
  // 更新图片数据
  updateUrlHandler(event) {
    if (event.formType === 'photoVideoSelectWidget') {
      this.formGroup.patchValue({ [event.subHtmlObj[0].formKey]: event.subHtmlObj[0].value });
      this.formGroup.patchValue({ [event.subHtmlObj[1].formKey]: event.subHtmlObj[1].value });

      if (event.subHtmlObj[1].formKeys && event.subHtmlObj[1].formKeys.indexOf(";") > -1) {
        const keyArray = event.subHtmlObj[1].formKeys.split(";");
        if (this.formGroup.contains(keyArray[0])) {
          this.formGroup.patchValue({ [keyArray[0]]: 'mp4' });
          this.formGroup.patchValue({ [keyArray[1]]: Number(event.subHtmlObj[1].size) });
        } else {
          this.formGroup.addControl(keyArray[0], new FormControl('mp4'));
          this.formGroup.addControl(keyArray[1], new FormControl(Number(event.subHtmlObj[1].size)));
        }
      }
      if (event.subHtmlObj && event.subHtmlObj.length === 3) {
        this.formGroup.patchValue({ [event.subHtmlObj[2].formKey]: event.subHtmlObj[2].value });
      }
      console.log('photoVideoSelectWidget:' + JSON.stringify(event));
    } else if (event.formType === 'fileSelectWidget') {
      this.formGroup.patchValue({ [event.formKey]: event.value });
      if (this.formGroup.contains(event.formKeys)) {
        
        this.formGroup.patchValue({ [event.formKeys]: event.valueN });
      } else {
        this.formGroup.addControl(event.formKeys, new FormControl(event.valueN));
      }
      
    }  else {
      this.formGroup.patchValue({ [event.formKey]: event.value });
      if (event.textType && event.textType === 'pdf') {
        if (event.formKeys && event.formKeys.indexOf(";")) {
          const keyArray = event.formKeys.split(";");
          if (this.formGroup.contains(keyArray[0])) {
            this.formGroup.patchValue({ [keyArray[0]]: event.valueLong});
            this.formGroup.patchValue({ [keyArray[1]]: event.valueIndex });
          } else {
            this.formGroup.addControl(keyArray[0], new FormControl(event.valueLong ));
            this.formGroup.addControl(keyArray[1], new FormControl(event.valueIndex ));
          }
        }
      }
    }
  }
  onValueChanged() {
    if (!this.formGroup) {
      return;
    }

    // tslint:disable-next-line:forin
    // for (const field in this.formErrors) {
    //   this.formErrors[field] = '';
    //   const control = form.get(field);
    //   if (control && control.dirty && !control.valid) {
    //     const messages = this.validationMessage[field];
    //     // tslint:disable-next-line:forin
    //     for (const key in control.errors) {
    //       this.formErrors[field] += messages[key] + '\n';
    //     }
    //   }
    // }
  }
  inputClick(item) {
    console.log('click input');
    if (item.disabled && item.tips) {
      this.appGlobalService.showToast(item.tips, 1500, "middle");
    }  else if (item.disabled && item.formType === 'detailAddress') {
      this.openModalMapPage(item)
    }
  }
  deleteValue(item) {
    if (item.value) {
      item.value = '';
      this.formGroup.patchValue({ [item.formKey]: item.value });
    }
  }
  beforeSubmit() {
    // tslint:disable-next-line:forin
    // for (const field in this.formErrors) {
    //   this.formErrors[field] = '';
    //   const control = form.get(field);

    //   if (control && !control.valid) {
    //     const messages = this.validationMessage[field];
    //     // tslint:disable-next-line:forin
    //     for (const key in control.errors) {
    //       this.formErrors[field] += messages[key] + '\n';
    //       if (field === 'userName') {
    //         this.onFocus = {
    //           focus: true
    //         };
    //       }
    //     }
    //     return false;
    //   } else {
    //     return true;
    //   }
    // }
  }
  // itemSuper : addItemCountList 
  sub(event, item, i, itemSuper?) {
    if (i === 0) {
      item.value = item.value - 0;
      item.value -= 1;
      if (item.minValue && item.minValue >= 0) {

      } else {
        item.minValue = 1; // 默认 1
      }

      if (item.value <= item.minValue) {
        item.value = item.minValue;
        event.stopPropagation();
        
      }

    } else if (i === 1) {
      item.value = item.value - 0;
      item.value += 1;
    }
    if (item.formType === 'addItemCountNoInput'){
      this.formGroup.patchValue({[item.formKey]:item.value})
    }
    this.updateAddItemCountListValue(itemSuper);
    event.stopPropagation();
  }
  updateAddItemCountListValue(itemSuper) {
    if (itemSuper && itemSuper.formType === "addItemCountList") {
      let temp: any = [];
      let tempShow: any = [];
      itemSuper.itemList.forEach(element => {
        if (element.value > 0) {
          temp.push(element.valueN + "-" + element.value);
          if (element.tagLabel && element.tagLabel.length > 0) {
            tempShow.push(element.label + "(" + element.tagLabel + ")" + "(" + element.value + itemSuper.unit + ")");
          } else {
            tempShow.push(element.label + " (" + element.value + itemSuper.unit + ")");
          }
        }
      });
      itemSuper.showValue = tempShow.join("<br>");
      itemSuper.value = temp.join(",");
      this.formGroup.patchValue({ [itemSuper.formKey]: itemSuper.value });
    }
  }
  inutValue(event, item, itemSuper?) {
    if (item.minValue && item.minValue >= 0) {

    } else {
      item.minValue = 1; // 默认 1
    }

    if (item.value <= item.minValue) {
      item.value = item.minValue;
    }
    this.updateAddItemCountListValue(itemSuper);
  }
  changeValue(event, item, itemSuper?) {
    item.value = event.detail.value;
    if (item.textType === 'Number' || item.textType === 'number') {
      
      if (event.detail && event.detail.value.length > Number(item.maxLength)) {
        item.value = Number(event.detail.value.toString().slice(0, Number(item.maxLength)));
        this.cd.markForCheck();
        this.cd.detectChanges();
      }
    } else {
      if (event.detail && event.detail.value.length > Number(item.maxLength)) {
        item.value = event.detail.value.toString().slice(0, Number(item.maxLength));
        this.cd.markForCheck();
        this.cd.detectChanges();
      }
    }

    this.formGroup.patchValue({ [item.formKey]: item.value });

    if (item.formType === 'getCashType' && item.showValue) {
      if (Number(item.value) > Number( item.showValue)) {
        item.value = item.showValue;
        this.formGroup.patchValue({ [item.formKey]: item.value });
      }
    }
    if (item.formType === 'textInputLJ') {
      if (item.value !== undefined && item.value !== '' && item.valueN !== undefined) {
        item.showValue = (item.value - 0) + '' + item.extra + ' ￥' + (item.value - 0) * item.valueN + `<br>`;
      } else if (item.value !== undefined && item.value !== ''
        && item.extra !== undefined && item.label !== undefined) {
        // 不展示价格
        item.showValue = item.label + "（" + (item.value - 0) + '' + item.extra + "）" + `<br>`;
      }
    }
    if (item.formType === 'slider') {
      if (event.detail.value >= item.itemList[item.itemList.length - 1].value) {
        item.showValue = '不限';
      } else {
        item.showValue = null;
      }
    }
    this.updateAddItemCountListValue(itemSuper);
  }

  // 实时检查电话
  // checkNow(item) {
  //   if (item.checkNow && item.submit && item.submit.id && item.value.length === 11) {
  //     const params = {
  //       content: { [item.formKey]: item.value },
  //       id: item.submit.id,
  //       sessionId: localStorage.getItem('sessionId')
  //     };
  //     this.http.post('application/submit', params, res => {
  //       if (res.message) {
  //         this.alert(res.message);
  //       }

  //     });
  //   }
  // }

  async alert(message, accout?) {
    const alert = await this.alertController.create({

      header: '',
      subHeader: '',
      message,
      buttons: [{
        text: '取消',
        role: 'cancel',
        cssClass: 'secondary',
        handler: (blah) => {
          console.log('取消');
        }
      }, {
        text: '确定',
        cssClass: 'LJ',
        handler: () => {
          console.log('继续');
          Object.assign(this.tagDataTemp, this.tagData);
          if (accout) {
            // const formItem = this.tagData[0];
            // formItem.showValue = this.formGroup.value[Object.keys(this.formGroup.value)[0]];
            // this.formGroup.patchValue({[Object.keys(this.formGroup.value)[0]]: accout});

            this.modalCtrl.dismiss({ form: this.formGroup }, '', 'showSearchModal');
            this.modalCtrl.dismiss({ form: this.formGroup });
          } else {
            this.modalCtrl.dismiss();
          }
        }
      },]
    });
    await alert.present();
  }
  switchCheck(value) {
    console.log('switch status:', value);

  }

  itemCheckChoose(){
    let check = true;
    this.tagData.forEach(item => {
      if (item.formType === "showSingleSelect") {
            let size = 0;
          item.itemList.forEach(e => {
            if (e.check) {
              size += 1;
            }
          });
          if (size < item.minSize) {
            if (item.lessTip && item.lessTip.length > 0) {
              this.appGlobalService.showToast(item.lessTip, 2000, 'top');
            } else {
              this.appGlobalService.showToast(`${item.label}至少选择${item.minSize}项`, 2000, 'top');
            }
            check = false;
            return;
          }
      }
    })
    return check;
  }
  sureBtn() {
    
    if (!this.itemCheckChoose()){
      return
    }
    const formKeyObj: any = {};
    if (this.formGroup.valid) {
      // console.log(this.formGroup.value);
      const params = this.formGroup.value;

      // tslint:disable-next-line:forin
      for (const prop in params) {
        if (Array.isArray(params[prop])) {
          params[prop] = params[prop].join(',');
        }
        // 删除无效值
        if (prop === '') {
          // delete params[prop];
        }
        if (prop.indexOf('cus_') > -1) {
          const p = prop.substring(4, prop.length - 1);
          formKeyObj[p] = formKeyObj[p] ? formKeyObj[p] : [];
          formKeyObj[p].push(params[prop]);
          this.formGroup.removeControl(prop);
          delete params[prop];
        }
      }
      // 组合表单值
      for (const key in formKeyObj) {
        if (Array.isArray(formKeyObj[key])) {
          const value = formKeyObj[key].join(',');
          this.formGroup.patchValue({ [key]: value });
        }
      }
      let compare = true;
      // tslint:disable-next-line:prefer-for-of
      for (let index = 0; index < this.compareItemArray.length; index++) {
        const compareItem = this.compareItemArray[index];
        if (Number(params[compareItem.minKey]) > Number(params[compareItem.maxKey])) {
          console.log(params[compareItem.minKey]);
          console.log(params[compareItem.maxKey]);
          if (compareItem.lessTip && compareItem.lessTip.length > 0) {
            this.appGlobalService.showToast(compareItem.lessTip, 3000, 'top');
          } else {
            this.appGlobalService.showToast(`最小${compareItem.label}不得大于/等于最大${compareItem.label}`, 3000, 'top');
          }

          compare = false;
          break;
        } else if (Number(params[compareItem.minKey]) === Number(params[compareItem.maxKey]) && Number(params[compareItem.minKey]) != 0) {
          console.log(params[compareItem.minKey]);
          console.log(params[compareItem.maxKey]);
          if (compareItem.canEqual) {
            continue;
          } else if (compareItem.lessTip && compareItem.lessTip.length > 0) {
            this.appGlobalService.showToast(compareItem.equalTip, 3000, 'top');
          } else {
            this.appGlobalService.showToast(`最小${compareItem.label}不得大于/等于最大${compareItem.label}`, 3000, 'top');
          }

          compare = false;
          break;
        }
      }
      if (compare) {
        console.log(params);

        if (this.showSearchModal === 2) {
          if (this.dataType === 1) {

            const addParams = {
              mobile: params[Object.keys(params)[0]],
              sessionId: localStorage.getItem("sessionId")
            };
            const that = this;

            this.http.post('user/addUser/', addParams, (res: any) => {
              // 返回值 int   0:成功    -1:账号已存在
              if (res.code === 0) {
                // // 输入手机号设置为showValue，userId 设置为value
                // const formItem = this.tagData[0];
                // formItem.showValue = params[Object.keys(params)[0]];
                // that.formGroup.patchValue({[params[Object.keys(params)[0]]]:res.data.userId});
                Object.assign(this.tagDataTemp, this.tagData);
                this.modalCtrl.dismiss({ form: that.formGroup }, '', 'showSearchModal');
                this.modalCtrl.dismiss({ form: that.formGroup });

              } else if (res.code === -1) {
                this.appGlobalService.showToast(res.message, 2000, 'middle');
              } else if (res.code === -2) {
                this.alert('账号已经存在，是否绑定该账户？', res.data.userId);
              } else {
                this.appGlobalService.showToast('出错了，请重试', 2000, 'middle');
              }
            });
          } else if (this.dataType === 0) {
            const addParams = {
              location: params.location, // "1245.125,45.214", // 坐标
              baseName: params.name, // "测试小区3", // 小区名称
              cityCode: params.city_id, // "4403", // 城市code
              areaCode: params.district_id, // "440303", // 区code
              address: params.address // "测试小区3"// 小区地址
            };
            const that = this;
            this.http.post('baseInfo/add/' + localStorage.getItem("sessionId"), addParams, (res: any) => {
              // 返回值 int   0:成功  1:未登录  -1:接口错误
              if (res === 0) {
                Object.assign(this.tagDataTemp, this.tagData);
                this.modalCtrl.dismiss({ form: that.formGroup, address: that.addressValue }, '', 'showSearchModal');
                this.modalCtrl.dismiss({ form: that.formGroup, address: that.addressValue });

              } else if (res === 1) {
                this.appGlobalService.showToast('登录已失效，请重新登录', 2000, 'middle');
              } else {
                this.appGlobalService.showToast('出错了，请重试', 2000, 'middle');
              }
            });
          }


        } else {
          if(this.tagData[0].formType === "textInputLJ"){
            for (const prop in this.formGroup.value) {
              if (prop === "count") {
                if(!this.formGroup.value[prop]){
                  this.getErrors(this.formGroup);
                  return;
                } else {
                  if(isNaN(this.formGroup.value[prop])){
                    this.appGlobalService.showToast('请填写1 ~ 9的数字', 2000, 'top');
                    return;
                  } else if(this.formGroup.value[prop] < 1){
                    this.appGlobalService.showToast('请填写1 ~ 9的数字', 2000, 'top');
                    return;
                  }
                }
              } else if (prop === "count2"){
                if(this.formGroup.value[prop]){
                  if(isNaN(this.formGroup.value[prop])){
                    this.appGlobalService.showToast('请填写1 ~ 9的数字', 2000, 'top');
                    return;
                  } else if(this.formGroup.value[prop] < 1){
                    this.appGlobalService.showToast('请填写1 ~ 9的数字', 2000, 'top');
                    return;
                  }
                }
              }
            }
          }

          Object.assign(this.tagDataTemp, this.tagData);
          this.modalCtrl.dismiss({ form: this.formGroup, address: this.addressValue });
        }

      }

    } else {
      this.getErrors(this.formGroup);
    }
  }

  getErrors(form) {
    const errs = [];
    for (const name in form.controls) {
      // eg: controls[name] = phone
      if (form.controls[name].errors) {
        errs.push({ key: [name], err: form.controls[name].errors });
      }
    }
    if (errs.length) {
      const errItem = errs[0];

      const firstErrMsgKey = Object.keys(errItem.err)[0];
      console.log(errItem.key, '校验的字段名');
      const messageObj = this.allLabel[errItem.key];
      let showMessage = messageObj[firstErrMsgKey];
      // if (errItem.err.required !== undefined) {
      //   showMessage = messageObj.required;
      // } else if (errItem.err.pattern !== undefined) {
      //   showMessage = messageObj.pattern;
      // } else
      if (errItem.err.rangeError !== undefined) {
        const label = messageObj.label.slice(-2);
        showMessage = `${messageObj.label}不得小于/等于最小${label}`;
      }
      // else {
      //   showMessage = '请输入正确的' + messageObj.label;
      // }

      this.appGlobalService.showToast(showMessage, 3000, 'top');

    }
  }




  onReset() {
    this.formGroup.reset();
  }

  afterChange(event) {
    console.log(event, 'afterChange');
  }

  inputErrorClick() {
    alert('At least four charactors for account');
  }

  inputChange() {
    // if (e.replace(/\s/g, '').length < 5 && e.replace(/\s/g, '').length > 0) {
    //   this.isError = true;
    // } else {
    //   this.isError = false;
    // }
    // this.formData.username = e;
  }
  // singleColumnSelect
  showActionSheet(item) {
    if (item.disabled) {
      if (item.tips && item.tips.length > 0) {
        this.appGlobalService.showToast(item.tips, 1500, "middle");
      }
      return;
    }
    // 如只有一个选项，且是model
    if (item.data && item.data.length === 1) {
      const data = item.data[0];
      if (data.type && data.type === 'modal') {
        this.openModalOfPersonSelect(item, data);
      }
    } else {
      const that = this;
      let lastIndex: -1;
      const buttons: any = [];
      item.data.forEach((element, index) => {
        buttons.push(element.label);
        if (element.value === item.value) {
          lastIndex = index;
        }
      });
      // 上次选择过
      if (lastIndex > -1) {
        ActionSheetService.showActionSheetWithOptions(
          {
            options: buttons,
            // cancelButtonIndex: BUTTONS.length - 1,
            destructiveButtonIndex: lastIndex,
            // title: 'title',
            // message: item.label,
            maskClosable: true
          },
          buttonIndex => {
            if (buttonIndex > -1) {
              console.log(item.data[buttonIndex]);
              that.selectItem(buttonIndex, item);

            }
          }
        );
      } else {
        // 第一次选择
        ActionSheetService.showActionSheetWithOptions(
          {
            options: buttons,
            maskClosable: true
          },
          buttonIndex => {
            if (buttonIndex > -1) {
              console.log(item.data[buttonIndex]);
              that.selectItem(buttonIndex, item);

            }
          }
        );
      }
    }
  }

  selectItem(index, item) {
    const data = item.data[index];
    if (!data.type || data.type === 'value') {
      this.formGroup.patchValue({ [item.formKey]: item.data[index].value });
      item.showValue = item.data[index].label;
      item.value = item.data[index].value;

      if (item.subHtmlObj && item.subHtmlObj.length > 0) {
        item.subHtmlObj.forEach(it => {
          if ((item.value && it.showCondition && (it.showCondition.indexOf(item.value) > -1 || item.value.indexOf(it.showCondition) > -1)) || !it.showCondition) {

            if ((it.formType === 'modalMultipleSelectLJ_AfterSubmit' || it.formType === 'modalMultipleSelect3_Full' || it.formType === 'modalMultipleSelect3_Auto_Full' || it.formType === 'modalMultipleSelect3_Full_Common') && it.submit) {

              it.submit.content = { [item.formKey]: item.value }
              if (it.formType === 'modalMultipleSelect3_Full' || it.formType === 'modalMultipleSelect3_Auto_Full' || it.formType === 'modalMultipleSelect3_Full_Common') {
                it.children = [];
              } else {
                it.data = [];
              }

              // 清空一下
              this.formGroup.patchValue({ [it.formKey]: '' });
              it.value = '';
              it.showValue = '';
              this.getIndustryData(it);

            }
          }
        });

      }
      this.checkSubHtmlObj(item);

    } else
      if (data.type && data.type === 'modal') {

        this.openModalOfPersonSelect(item, data);
      }

  }
  checkDateTime(item){
    if (item.eventName === 'sendDateTime' && item.formType === 'switchButtonFW_3') {
      this.tagData.forEach(element => {
        if (element.eventName === 'getDateTime' && element.formType === 'sectionDesc') {
          let date = new Date(element.value);  
           // 定义格式化选项  
          const options = {  
            year: 'numeric', 
            month: '2-digit', 
            day: '2-digit',  
            hour: '2-digit',
            minute: '2-digit', 
            second: '2-digit',  
            hour12: false // 使用24小时制  
        };  
        
          // date.setDate(date.getSeconds() ); // 按秒+  
          console.log(date.valueOf())
          date.setTime(date.valueOf() + this.appGlobalService.getInterger(item.value)*1000 )

          // // 转换为新的时间格式化字符串  
          // let newTimeString = date.toISOString().slice(0, 19).replace('T', ' ');  
          // console.log(newTimeString); // 输出新的时间字符串
          
          // console.log(date.toLocaleString('zh-CN', options)); // 输出新的时间字符串
          let newTimeString = this.currentDateFormat(date,'yyyy-mm-dd HH:MM:ss')
          console.log(newTimeString); // 输出新的时间字符串
          element.showValue =  newTimeString;
          if (element.formKey) {
            this.formGroup.patchValue({ [element.formKey]: element.showValue });// 在value的基础上加减的，所以用 showValue最终值。
          }

        }
        
      });
    }
  }

  // 遍历是否有需要展开或者隐藏的
  checkSubHtmlObj(item) {
    const that = this;
    if (item.formType === 'modalOfLocalEdit') {
      return;
    }
    if (item.subHtmlObj && item.subHtmlObj.length > 0) {
      let temp: any = null;
      let tempAdd: any = [];
      try {
        item.subHtmlObj.forEach(element => {

          if (item.formType === 'nextPageFomObj') {
            this.nextPageFomObj = item;
            // this.cd.detectChanges();
            throw new Error('break');

          }
          if (element.showCondition && !(item.value === null || item.value === undefined) &&
            ( element.showCondition.indexOf(item.value) > -1 ||
              (item.value.indexOf(element.showCondition) > -1) ||
              (item.value.indexOf(element.showCondition2) > -1))) {
            // 子项 Key 相同的情况 add del 是相同的
            if (item.subHtmlObj.length > 1 && item.subHtmlObj[0].formKey === item.subHtmlObj[1].formKey) {
              temp = element;
            } else {
              that.addSubFormControl(element);
              tempAdd.push(element);
            }
          } else if (element.showCondition &&  !(item.value === null || item.value === undefined) &&
            !( element.showCondition.indexOf(item.value) > -1 ||
              ( item.value.indexOf(element.showCondition) > -1) ||
              (item.value.indexOf(element.showCondition2) > -1))) {
            // 处理子项key 相同 但使用条件不一样
            let canDel = true;
            tempAdd.forEach(e => {
              if (e.formKey === element.formKey) {
                canDel = false;
              }
            });
            if (canDel) {
              that.removeFormControl(element);
            }
          } else if (!element.showCondition) {
            that.addSubFormControl(element);
            tempAdd.push(element);
          }
          if (temp !== null) {
            that.addSubFormControl(temp);
          }

        });
      } catch (error) {
        if (error.message !== 'break') {
          throw error;
        }
      }

    }

  }

  addSubFormControl(formItem) {
    this.addFormControl(formItem);
    // if (formItem.subHtmlObj && formItem.subHtmlObj.length) {
    //   formItem.subHtmlObj.forEach(element => {
    //     this.addSubFormControl(element);
    //   });
    // }
  }


  changeItemobjValidator(item, type?, i?) {
    const that = this;
    if (type === 'contractSelectWidget') {
      item.value = item.value === 'true' ? 'false' : 'true';
      this.formGroup.patchValue({ [item.formKey]: item.vaule });
      if (item.value === 'true') {
        console.log('show1');
        item.subHtmlObj.forEach(element => {
          that.addFormControl(element);
        });

      } else {
        item.subHtmlObj.forEach(element => {
          that.removeFormControl(element);
        });
        console.log('hidde');
      }
    } else if (type === 'multipleColumnSelect') {
      console.log(item.value);
    } else if (type === 'quickRelease') {
      item.value = item.value === 'true' ? 'false' : 'true';
      this.formGroup.patchValue({ [item.formKey]: item.value });
    } else if (type === 'checkBox') {
      item.value = item.value === '1' ? '0' : '1';
      this.formGroup.patchValue({ [item.formKey]: item.value });
    } else if (type === 'showSingleSelect') {
      if (item.disabled) {
        if (item.tips && item.tips.length > 0) {
          this.appGlobalService.showToast(item.tips, 1500, "middle");
        }
        return;
      }
      // 增加 多选支持
      if (item.multiSelect === true || item.multiSelect === "true") {
        let value = '';
        const valueArray: any = [];
        const labelsArray: any = [];
        if (item.minSize && item.minSize > 0 && i.check) {
          let size = 0;
          item.itemList.forEach(e => {
            if (e.check) {
              size += 1;
            }
          });
          if (size < item.minSize) {
            if (item.lessTip && item.lessTip.length > 0) {
              this.appGlobalService.showToast(item.lessTip, 2000, 'top');
            } else {
              this.appGlobalService.showToast(`${item.label}至少选择${item.minSize}项`, 2000, 'top');
            }
            return;
          }
        }
        i.check = !i.check;
        item.itemList.forEach(e => {
          if (e.check) {
            valueArray.push(e.value);
            labelsArray.push(e.label);
          }
        });
        value = valueArray.join(',');
        item.value = value;
        if (item.sep !== undefined) {
          value = valueArray.join(item.sep);
        }
        item.showValue = labelsArray.join('、');
        this.formGroup.patchValue({ [item.formKey]: item.value });

      } else {
        if (i.check) {
          item.value = i.value;
          if (i.formObj && i.formObj.length > 0) {
            // add
            i.formObj.forEach(e => {
              this.addFormControl(e);
            });
          }
        } else {
          item.itemList.forEach(element => {
            if (element === i) {
              i.check = true;
              item.value = i.value;
              item.showValue = i.label;
              if (i.formObj && i.formObj.length > 0) {
                // add
                i.formObj.forEach(e => {
                  that.addFormControl(e);
                });
              }
            } else {
              if (element.check && element.formObj && element.formObj.length > 0) {
                // remove
                element.formObj.forEach(e => {
                  that.removeFormControl(e);
                });
              }
              element.check = false;

            }
          });
        }
      }
      
      this.checkSubHtmlObj(item);
      console.log(item.value);
      this.formGroup.patchValue({ [item.formKey]: item.value });

    } else if (type === 'switchButton' ||
      type === 'switchButtonLJ' ||
      type === 'switchButtonLJ_icon' ||
      type === 'switchButtonFW' ||
      type === 'switchButtonFW_3' ||
      type === 'switchButtonJoin' ||
      type === 'radioButtonLJ' ||
      type === 'radioButton' ||
      type === 'chooseGrade') {
      if (item.itemList[i].link && item.itemList[i].link.target) {
        this.pageModalService.openPage(item.itemList[i].link);
        return;
      }
      // 增加 多选支持
      if (item.multiSelect === true) {
        const valueArray: any = [];
        let value = '';
        item.itemList[i].check = !item.itemList[i].check;
       // 支持最多选择数目 max
       if (item.max > 1) {
        let maxN = 0;
        item.itemList.forEach(e => {
          if (e.check) {
            maxN += 1;
          }
        });
        if (maxN > item.max) {
          item.itemList[i].check = !item.itemList[i].check;
          if (item.lessTip && item.lessTip.length > 0) {
            this.appGlobalService.showToast(item.lessTip, 1500, "middle");
          }
        } 
      } else {
        // 互斥
        if (item.itemList[i].radio === true && item.itemList[i].check === true) {
          item.itemList.forEach(e => {
            if (e.check && e.radio) {

            } else {
              e.check = false;
            }
          });
        } else if (item.itemList[i].check === true) {
          item.itemList.forEach(e => {
            if (e.check && e.radio) {
              e.check = false;
            }
          });
        }

      }
      setTimeout(() => {
          if (this.fwInputM) {
            this.fwInputM.setFocus();
          }
        }, 150);
        item.itemList.forEach(e => {
          if (e.check) {
            valueArray.push(e.value);
          }
        });
        value = valueArray.join(';');
        if (item.sep !== undefined) {
          value = valueArray.join(item.sep);
        }
        item.value = value;
        this.formGroup.patchValue({ [item.formKey]: item.value });

      } else {
        if (item.itemList[i].check) {
          return;
        } else {
          item.itemList[i].check = true;
          item.showValue = item.itemList[i].label;
          // 主页下单
          if(this.tagData[1] !== undefined && this.tagData[1].unit && item.itemList[i].unit && item.itemList[i].valueN){
            if (item.itemList[i].unit === '￥') {
              item.showValue = item.itemList[i].label + '<br>' + "("+ this.tagData[1].value+ this.tagData[1].unit +") "+item.itemList[i].unit + item.itemList[i].valueN;
            } else {
              item.showValue = item.itemList[i].label + '<br>' + "("+ this.tagData[1].value+ this.tagData[1].unit +") "+ item.itemList[i].valueN +item.itemList[i].unit ;
            }
            
          } else if (item.itemList[i].unit && item.itemList[i].valueN) {
            if (item.itemList[i].unit === '￥') {
              item.showValue = item.itemList[i].label + ' ' + item.itemList[i].unit + item.itemList[i].valueN;  
            } else {
              item.showValue = item.itemList[i].label + ' '+ item.itemList[i].valueN  + item.itemList[i].unit ;
            }
            
          }
          item.value = item.itemList[i].value;
          this.formGroup.patchValue({ [item.formKey]: item.value });
          
        }
        item.itemList.forEach(e => {
          if (item.itemList[i] !== e) {
            e.check = false;
          }
        });
      }
      this.checkSubHtmlObj(item);
      this.checkDateTime(item);
    } else if (type === 'joinLink') {
      item.checked = !item.checked;
      item.value = item.checked ? '1' : '';
      this.formGroup.patchValue({ [item.formKey]: item.value });
    } else if (type === 'multipleInterestSelect') {
      let value = '';
      let valueArray: any = [];
      item.data[i].check = !item.data[i].check;
      item.data.forEach(e => {
        if (e.check) {
          valueArray.push(e.value);
        }
      });
      value = valueArray.join(';');
      if (item.sep !== undefined) {
        value = valueArray.join(item.sep);
      }
      item.value = value;
      this.formGroup.patchValue({ [item.formKey]: item.value });
    }
  }
  async showMultipleColumnSelect(item) {
    if (!item.data || item.data.length === 0) {
      if (item.tips && item.tips.length > 0) {
        this.appGlobalService.showToast(item.tips, 1500, "middle");
      }
      return;
    }
    const modal = await this.modalCtrl.create({
      showBackdrop: true,
      cssClass: 'modal-m-select',
      component: ModalOfSelectComponent,
      componentProps: { tagData: item }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    const array = [];
    const arrayValue = [];
    modalData.data.data.data.forEach(element => {
      if (element.check) {
        array.push(element.label);
        arrayValue.push(element.value);
      }
    });
    item.showValue = array.join(',');
    item.value = arrayValue.join(',');
    if (item.sep !== undefined) {
      item.value = arrayValue.join(item.sep);
    }
    this.formGroup.patchValue({ [item.formKey]: item.value });
    if (item.subHtmlObj && (item.subHtmlObj[0].formType === 'multipleColumnSelect' || item.subHtmlObj[0].formType === 'modalMultipleSelectLJ_AfterSubmit' || item.subHtmlObj[0].formType === 'modalMultipleSelect3_Full' || item.subHtmlObj[0].formType === 'modalMultipleSelect3_Auto_Full') && item.subHtmlObj[0].submit) {

      item.subHtmlObj[0].submit.content = { [item.formKey]: item.value }
      if (item.subHtmlObj[0].formType === 'modalMultipleSelect3_Full' || item.subHtmlObj[0].formType === 'modalMultipleSelect3_Auto_Full' || item.subHtmlObj[0].formType === 'multipleColumnSelect') {
        item.subHtmlObj[0].children = [];
      } else {
        item.subHtmlObj[0].data = [];
      }

      // 清空一下
      this.formGroup.patchValue({ [item.subHtmlObj[0].formKey]: '' });
      item.subHtmlObj[0].value = '';
      item.subHtmlObj[0].showValue = '';
      this.getIndustryData(item.subHtmlObj[0]);

    }
    this.checkSubHtmlObj(item);
  }
  // 打开行业模态框
  async openMultipleModal(item, isArea?) {
    if (!item.data || item.data.length === 0) {
      if (item.tips && item.tips.length > 0) {
        this.appGlobalService.showToast(item.tips, 1500, "middle");
      }
      return;
    }
    const that = this;
    const modal = await this.modalCtrl.create({
      component: ModalOfMultipleComponent,
      componentProps: { data: item },
      cssClass: item.formType.indexOf('LJ') > -1 ? 'LJ-modal-multiple' : "",
    });
    modal.onDidDismiss().then(function (data) {
      if (data.data) {
        const selectedData = data.data;
        const selectedLabel = selectedData.map(v => {
          return v.label;
        });
        const selectedValue = selectedData.map(v => {
          return v.value;
        });
        that.formGroup.patchValue({ [item.formKey]: selectedValue });
        item.value = selectedValue;
        item.showValue = selectedLabel;
      }
    });
    return await modal.present();
  }

  // 打开选择人员模态框
  async openModalOfPersonSelect(item, data) {
    const that = this;
    if (item.value && item.value !== '') {
      data.selectValue = item.value;
    }
    const modal = await this.modalCtrl.create({
      component: ModalOfPersonSelectComponent,
      componentProps: { value: data }
    });
    modal.onDidDismiss().then(function (data) {
      if (data.data && data.data.data) {
        const selectedData = data.data.data;

        that.formGroup.patchValue({ [item.formKey]: selectedData.value });
        item.value = selectedData.value;
        item.showValue = selectedData.label;
      }
    });
    return await modal.present();
  }

  // 编辑更多
  async openModalMoreEditInfo(item, showSearchModal?, nextStep?) {

    if (item.disabled) {
      if (item.tips && item.tips.length > 0) {
        this.appGlobalService.showToast(item.tips, 1500, "middle");
      }

      return;
    }
    if (nextStep) {
      for (const cons in this.formGroup.controls) {
        if (this.allForm.contains(cons)) {
          this.allForm.patchValue({ [cons]: this.formGroup.controls[cons].value });
        } else {
          this.allForm.addControl(cons, new FormControl(this.formGroup.controls[cons].value));
        }

      }
    }
    if (!showSearchModal) {
      showSearchModal = item.showSearchModal ? 1 : 0
    }
    let id = ''
    if (showSearchModal) {
      id = 'showSearchModal';
      this.pageModalService.addModeId(id);
    } else if (item.showValue === 'NoShowSubmit') {
      id = 'NoShowSubmit';
      this.pageModalService.addModeId(id);
    }
    if (id === ''){
      id = this.pageModalService.addModeId();
    }
    this.modalId = id;
    const that = this;
    const modal = await this.modalCtrl.create({
      component: ModalOfEditMoreInfoComponent,
      componentProps: { value: item, showSearchModal, nextStep, allForm: this.allForm, cssStyle: item.modalCssStyle,cssClass: item.modalCssStyle },
      id,
      cssClass: item.modalCssStyle ? "auto-modal" : "",
      enterAnimation: item.showAnimation ? ModalFromRightEnter : null,
      leaveAnimation: item.showAnimation ? ModalFromRightLeave : null
    });
    modal.onDidDismiss().then((data) => {
      if (data.data && data.data.form) {
        const hiddenForm: FormGroup = data.data.form;
        // tslint:disable-next-line:forin
        for (const cons in hiddenForm.controls) {
          that.formGroup.patchValue({ [cons]: hiddenForm.controls[cons].value });
        }
        // 左邻右舍
        if (item.formType === 'commaSpliceShowValueForm') {
          const array: Array<string> = [];
          item.subHtmlObj.forEach(element => {
            // 赋值
            if (element.formType === 'multipleForm') {
              element.value = hiddenForm.controls[element.formKey].value;
              if (element.subHtmlObj.length && element.subHtmlObj[0].formKey.indexOf('cus_') > -1) {

                const a = element.value.split(',');
                a.forEach(e => {
                  if (e && e !== '') {
                    array.push(e);
                  }
                });

              }
            }

          });
          item.showValue = array.join(',');
        } else if (item.formType === 'modalOfTextArea') {
          item.showValue = hiddenForm.controls[item.subHtmlObj[0].formKey].value;
        } else if (item.formType === 'selectAddressWidget' || item.formType === 'selectAddressWidgetLJ') {
          const address = data.data.address;
          if (address) {
            that.address = address;
            if (item.subHtmlObj.length > 2) {
              item.value = item.subHtmlObj[0].showValue +
                item.subHtmlObj[0].subHtmlObj[0].showValue +
                item.subHtmlObj[1].value +
                (item.subHtmlObj[2].value ? item.subHtmlObj[2].value : '');
            } else if (item.subHtmlObj.length > 1) {
              item.value = item.subHtmlObj[0].showValue + item.subHtmlObj[0].subHtmlObj[0].showValue + item.subHtmlObj[1].value;
            }
            item.value = item.value.replace('undefined',''); 
            item.showValue = item.value;
            that.formGroup.patchValue({ [item.formKey]: item.value });
          }
        } else if (item.formType === 'modalOfMoreItems' ||
          item.formType === 'modalOfMoreItemsDesign' ||
          item.formType === 'bottomModalOfMoreItemsFW' ||
          item.formType === 'modalOfMoreItemsFW') {

          //?  1.9.18 add eventName  用于更新 时间和 价格合计
          //?  eventName="sendUnit" 表示 选择服务规格 发送unit到 上门时间 eventName="receiverUnit"接收
          if (item.eventName === "sendUnit") {
            // console.log('msg---->',this.tagData );
            that.tagData.forEach(e => {
              if (e.formType === "bottomModalOfMoreItemsFW") {
                if (e.subHtmlObj[0].eventName === "receiverUnit") {

                  item.subHtmlObj[0].itemList.forEach(element => {
                    if (element.check === true) {
                      e.subHtmlObj[0].unit = element.timeUnit
                    }
                  });

                }
              }
            })
          }

          if (item.eventType === 'updateTotalAmount') {
            // console.log('data.data=',data.data);
            // console.log('item=',item);
            // that.eventService.eventEmit.emit('updateCleanerShopOrdersAmount', 'test');

            //  that.eventService.eventEmit.emit("updateCleanerShopOrdersAmount", 500);

            // let sendTotalAmount = 0;
            // 1.9.17.3  1.全屋大扫除 2.日常清洁 选择服务规格 更新价格 3.家电清洗 - 空调清洗
            if (item.subHtmlObj && item.subHtmlObj[0] && item.subHtmlObj[0].formType === 'switchButtonFW_3') {
              if (item.subHtmlObj[1].formType === 'addItemCount') {
                item.subHtmlObj[0].itemList.forEach(element => {
                  if (data.data.form && data.data.form.value[item.subHtmlObj[0].formKey] !== undefined) {
                    if (element.value === data.data.form.value[item.subHtmlObj[0].formKey]) {
                      let totalAmount = element.valueN * item.subHtmlObj[1].value;
                      that.eventService.eventEmit.emit("updateCleanerShopOrdersAmount", totalAmount);
                    }
                  }
                });
              } else {
                item.subHtmlObj[0].itemList.forEach(element => {
                  if (data.data.form && data.data.form.value[item.subHtmlObj[0].formKey] !== undefined) {
                    if (element.value === data.data.form.value[item.subHtmlObj[0].formKey]) {
                      that.eventService.eventEmit.emit("updateCleanerShopOrdersAmount", element.valueN);
                    }
                  }
                });
              }

              // 1.9.17.3 家居清洁 -> 布艺沙发清洁
            } else if (item.subHtmlObj && item.subHtmlObj[0] && item.subHtmlObj[0].formType === 'addItemCountList') {
              let totalAmount = 0;
              let tempFormData = data.data.form.value[item.subHtmlObj[0].formKey];
              item.subHtmlObj[0].itemList.forEach(element => {
                if (data.data.form && tempFormData !== undefined) {
                  if (element.firstValue !== undefined) {
                    totalAmount += element.firstValue * element.value;
                  }
                }
              });
              that.eventService.eventEmit.emit("updateCleanerShopOrdersAmount", totalAmount);
            }
            // 1.9.17.3 家居清洁 -> 布艺沙发清洁
            else if (item.subHtmlObj && item.subHtmlObj[0] && item.subHtmlObj[0].formType === 'textInputLJ') {
              let totalAmount = 0;
              item.subHtmlObj.forEach(element => {
                if (element.valueN !== undefined && element.formType === 'textInputLJ') {
                  totalAmount += element.valueN * element.value;
                }
              });
              that.eventService.eventEmit.emit("updateCleanerShopOrdersAmount", totalAmount);
            }
          }
          if (item.subHtmlObj && (item.subHtmlObj[0].formType === 'multipleSelect3' || item.subHtmlObj[0].formType === 'multipleSelect') && hiddenForm.controls[item.subHtmlObj[0].formKey].value) {
            let showValue: any = '';
            item.subHtmlObj[0].children.forEach(big => {
              if (big.checked) {
                showValue += `<font color="#45474D">` + big.label + `<font>` + '、';
              } else {
                let str = ''
                let str2 = ''
                let str1 = ''
                // 2
                big.children.forEach(m => {
                  m.checked ? str2 += m.label + '、' : '';
                  if (!m.checked && m.children && m.children.length > 0) {
                    // 3
                    let str3 = '';
                    m.children.forEach(s => {
                      s.checked ? str3 += s.label + '、' : '';
                    });

                    if (str3.length > 0) {
                      str2 = m.label + '-' + str3
                    }
                  }
                  if (str2.length > 0) {
                    str1 += `<font color="#7E838C">` + str2 + `<font>`
                    str2 = '';
                  }

                });
                if (str1.length > 0) {
                  showValue += `<font color="#45474D">` + big.label + `<font>` + '-' + str1
                  //`<font color="#7E838C">` +'-' + str + `<font>` ;
                }
              }

            });
            showValue = showValue.substring(0, showValue.lastIndexOf('、'));

            item.showValue = showValue;
            console.log('multipleSelect3:' + showValue);

          } else if (item.subHtmlObj && item.showIndexs && item.showIndexs.indexOf(',') > -1) {
            // 支持展示多个子项值 ，隔开
            const indexs = item.showIndexs.split(",");
            let values: any = [];
            indexs.forEach(element => {
              if (item.subHtmlObj[element].showValue) {
                values.push(item.subHtmlObj[element].showValue);
              } else {
                values.push(hiddenForm.controls[item.subHtmlObj[element].formKey].value);
              }
            });
            item.showValue = values.join(',');

          } else if (item.subHtmlObj && item.showIndex < item.subHtmlObj.length) {
            // 优先展示showValue
            if (item.subHtmlObj[item.showIndex].showValue) {
              item.showValue = item.subHtmlObj[item.showIndex].showValue;
            } else {
              item.showValue = hiddenForm.controls[item.subHtmlObj[item.showIndex].formKey].value;
            }
          } else {

          }
        } else if (item.formType === 'editMultipleSelect') {

          if (item.subHtmlObj[0].formType === 'multipleSelect' && hiddenForm.controls[item.subHtmlObj[0].formKey].value) {
            let showValue: any = '';
            item.subHtmlObj[0].children.forEach(big => {
              if (big.checked) {
                showValue += `<font color="#45474D">` + big.label + `<font>` + '、';
              } else {
                let s = '';
                big.children.forEach(small => {
                  small.checked ? s += small.label + '、' : '';
                });
                if (s.length > 0) {
                  showValue += `<font color="#45474D">` + big.label + `<font>` + `<font color="#7E838C">` + '-' + s + `<font>`;
                }
              }

            });
            showValue = showValue.substring(0, showValue.lastIndexOf('、'));

            item.showValue = showValue;
          } else if (item.subHtmlObj[0].formType === 'multipleSelect3' && hiddenForm.controls[item.subHtmlObj[0].formKey].value) {
            let showValue: any = '';
            item.subHtmlObj[0].children.forEach(big => {
              if (big.checked) {
                showValue += `<font color="#45474D">` + big.label + `<font>` + '、';
              } else {
                let str = ''
                let str2 = ''
                let str1 = ''
                // 2
                big.children.forEach(m => {
                  m.checked ? str2 += m.label + '、' : '';
                  if (!m.checked && m.children && m.children.length > 0) {
                    // 3
                    let str3 = '';
                    m.children.forEach(s => {
                      s.checked ? str3 += s.label + '、' : '';
                    });

                    if (str3.length > 0) {
                      str2 = m.label + '-' + str3
                    }
                  }
                  if (str2.length > 0) {
                    str1 += `<font color="#7E838C">` + str2 + `<font>`
                    str2 = '';
                  }

                });
                if (str1.length > 0) {
                  showValue += `<font color="#45474D">` + big.label + `<font>` + '-' + str1
                  //`<font color="#7E838C">` +'-' + str + `<font>` ;
                }
              }

            });
            showValue = showValue.substring(0, showValue.lastIndexOf('、'));

            item.showValue = showValue;
            console.log('multipleSelect3:' + showValue);
          } else {
            if (item.subHtmlObj[item.showIndex].showValue) {
              item.showValue = item.subHtmlObj[item.showIndex].showValue;
            } else {
              item.showValue = hiddenForm.controls[item.subHtmlObj[item.showIndex].formKey].value;
            }
          }

        }
      }
    });
    return await modal.present();
  }
  // <!-- 行业 区域 单选 双联picker-->
  pickerSelect(result, item, isArea?) {
    if (result && result.length && Array.isArray(result)) {
      if (result.length === 1) {
        item.value = result[0].value;
        item.showValue = `${result[0].label}`;
      } else if (result.length === 2) {
        item.value = result[1].value;
        item.showValue = `${result[0].label} ${result[1].label}`;
        if(item.minSize && item.minSize == 1) {
          item.showValue = `${result[1].label}`;
        }
      } else {
        item.value = result[2].value;
        item.showValue = `${result[0].label} ${result[1].label} ${result[2].label}`;
        if(item.minSize && item.minSize == 1) {
          item.showValue = `${result[2].label}`;
        }
      }
      if (item['isArea']) {
        this.addressValue.area = item.showValue;
        this.addressValue.areaCode = item.value;
        this.bigDistrict = item.showValue;
        this.getPointByCityName(this.positionInfo.name, item.showValue);
      }

      this.formGroup.patchValue({ [item.formKey]: item.value });
      if (item.subHtmlObj && item.subHtmlObj.length > 0 && (item.subHtmlObj[0].formType === 'multipleColumnSelect' || item.subHtmlObj[0].formType === 'multipleColumnSelectJoin' || item.subHtmlObj[0].formType === 'multipleColumnSelectTwoLine') && item.subHtmlObj[0].submit) {
        item.subHtmlObj[0].submit.content = { [item.formKey]: item.value }
        item.subHtmlObj[0].data = [];
        // 清空一下
        this.formGroup.patchValue({ [item.subHtmlObj[0].formKey]: '' });
        item.subHtmlObj[0].value = '';
        item.subHtmlObj[0].showValue = '';
        this.getIndustryData(item.subHtmlObj[0])

      }
    }
    this.checkSubHtmlObj(item);

  }
  cityClick(city, item) {
    city.isSelected = !city.isSelected;
    if (city.isSelected && item.selectedCityIds.indexOf(city.i) === -1) {
      item.selectedCityIds.push(city.i);
      item.selectedCityName.push(city.n);
    } else {
      item.selectedCityIds.splice(item.selectedCityIds.indexOf(city.i), 1);
      item.selectedCityName.splice(item.selectedCityName.indexOf(city.n), 1);
    }

    console.log((item.selectedCityIds).join(','));
    item.value = item.selectedCityIds.join(',');
    if (item.sep !== undefined) {
      item.value = item.selectedCityIds.join(item.sep);
    }
    
    item.showValue = item.selectedCityName.join(',');
    this.formGroup.patchValue({ [item.formKey]: item.value });

  }
  async getCityData(item) {

    const params = {
      content: {},
      id: item.submit.id,
      sessionId: localStorage.getItem('sessionId')
    };

    await this.http.post('application/submit', params, res => {

      if (res.data.data) {
        if (item.formType === 'threeLevelSelection') {
          item.children = res.data.data;
          this.initThreeLevelData(item);
        } else {
          item.groupCities = res.data.data.data;
          item.selectedCityIds = [];
          item.selectedCityName = [];
          item.groupCities.forEach(element => {
            element.c.forEach(e => {
              if (e.isSelected && item.selectedCityIds.indexOf(e.i) === -1) {
                item.selectedCityIds.push(e.i);
                item.selectedCityName.push(e.n);
              }
            });
          });
          console.log(JSON.stringify(item.selectedCityIds));
          item.value = item.selectedCityIds.join(',');
          if (item.sep !== undefined) {
            item.value = item.selectedCityIds.join(item.sep);
          }
          item.showValue = item.selectedCityName.join(',');
          this.formGroup.patchValue({ [item.formKey]: item.value });
        }
        

      } else {
        // 请求数据失败
        this.appGlobalService.showToast(res.message, 2000, 'middle');
      }
    });
  }

  initThreeLevelData(item) {
    if (item.children && item.children[0]) {
      item.children[0].open = true;
      item.current = item.children[0]; // 2
      if (item.formType === 'threeLevelSelection' && item.current.children &&  item.current.children[0]) {
        item.current.current = item.current.children[0]; // 3
        item.current.children[0].open = true;
      } 
    }

    if (item.value) {
      // formItem.showValue = formItem.value;
      //初始化赋值
      if (typeof item.value === 'string' ) {
        item.value = item.value.split(',')

      } else if (Array.isArray(item.value)) {
        
      } else {
        item.value = [];
      }
      let openBig: any;
      item.children.forEach(big => {
        if (item.value.indexOf(big.value) > -1) {
          big.checked = true;
          big.hasValue = true;
          if (openBig === undefined){
            openBig = big;
          }
          // 2
          big.children.forEach(m => {
            m.checked = true;
            m.hasValue = true;
            if (openBig === undefined){
              openBig = big;
            }
            if (m.children && m.children.length > 0) {
              // 3
              m.children.forEach(s => {
                s.checked = true;
                if (openBig === undefined){
                  openBig = big;
                }
              });
            }

          });


        } else {
          big.children.forEach(m => {
            // 2
            if (item.value.indexOf(m.value) > -1) {
              m.checked = true;
              m.hasValue = true;
              big.hasValue = true;
              if (openBig === undefined){
                openBig = big;
              }
            }
            if (m.children && m.children.length > 0) {
              // 3
              m.children.forEach(s => {
                if (m.checked) {
                  s.checked = true;
                  if (openBig === undefined){
                    openBig = big;
                  }
                } else {
                  if (item.value.indexOf(s.value) > -1) {
                    s.checked = true;
                    m.hasValue = true;
                    big.hasValue = true;
                    if (openBig === undefined){
                      openBig = big;
                    }
                  }
                }


              });
            }
          });
        }

      });

      if (openBig){
        item.children[0].open = false;
        openBig.open = true;
        item.current = openBig;
  
        if (item.formType === 'threeLevelSelection' && item.current.children &&  item.current.children[0]) {
          item.current.current = item.current.children[0]; // 3
          item.current.children[0].open = true;
        } 
      }
    }
  }
  // 打开部门
  async openModalDepartmentPage(item) {
    const modal = await this.modalCtrl.create({
      component: ChooseDepartmentComponent,
      componentProps: { tagData: item.link, modalTitle: "选择部门", backValue: true }
    });
    modal.onDidDismiss().then((data) => {

      if (data.data) {

        this.formGroup.patchValue({ [item.formKey]: data.data.code });
        item.showValue = data.data.name;
      }
    });
    return await modal.present();
  }

  // 打开城市选择
  async openModalCityPage(item) {
    if (item.disabled) {
      if (item.tips && item.tips.length > 0) {
        this.appGlobalService.showToast(item.tips, 1500, "middle");
      }

      return;
    }
    const that = this;
    const modal = await this.modalCtrl.create({
      component: ChooseCityComponent,
      componentProps: { value: item.link.target, modalTitle: item.usePlaceHolderAsTitle? item.placeHolder :  item.label, noStorage: true }
    });
    modal.onDidDismiss().then(function (data) {
      const value = data.data;
      if (value !== undefined && value.n !== undefined) {
        that.pageCity = value.n;
        that.pageCityCode = value.i;
        that.addressValue.city = value.n;
        item.showValue = value.n;
        item.value = value.i;
        that.formGroup.patchValue({ [item.formKey]: value.i });
        if (item.subHtmlObj && item.subHtmlObj.length === 1) {
          that.getAreaData(item, true);
          item.subHtmlObj[0].showValue = "";
          that.getPointByCityName(item);
        }

      }
    });
    return await modal.present();
  }

  async getIndustryData(item) {
    const params = {
      content: item.submit.content ? item.submit.content : {},
      id: item.submit.id,
      sessionId: localStorage.getItem('sessionId')
    };
    // 请求获取新数据
    await this.http.post('application/submit', params, res => {
      // 请求数据成功 重置区域数据
      if (res.data.data) {
        if (item.formType === 'modalMultipleSelect3_Full' || item.formType === 'modalMultipleSelect3_Auto_Full' ||
          item.formType === 'modalMultipleSelect3_Full_Common') {
          item.children = res.data.data;
        } else {
          item.data = res.data.data;
        }
        // 自动请求下级
        if (item.value && (item.formType === 'pickerSelect' || item.formType === 'pickerSelectTwoLine' || item.formType === 'pickerSelectJoin')) {
          if (item.subHtmlObj && item.subHtmlObj.length > 0 && (item.subHtmlObj[0].formType === 'multipleColumnSelect' || item.subHtmlObj[0].formType === 'multipleColumnSelectJoin' || item.subHtmlObj[0].formType === 'multipleColumnSelectTwoLine') && item.subHtmlObj[0].submit) {
            item.subHtmlObj[0].submit.content = { [item.formKey]: item.value }
            item.subHtmlObj[0].data = [];
            // 清空一下
            this.formGroup.patchValue({ [item.subHtmlObj[0].formKey]: '' });
            item.subHtmlObj[0].value = '';
            item.subHtmlObj[0].showValue = '';
            this.getIndustryData(item.subHtmlObj[0])

          }
        }
      } else {
        // 请求数据失败
        this.appGlobalService.showToast(res.message, 2000, 'middle');
      }
    });
  }
  openPage(item) {
    this.pageModalService.openPage(item);
  }
  async getAreaData(item, resetArea?) {
    if (!item.subHtmlObj) {
      return;
    }
    let content: any = {}
    if (item.submit.content !== undefined) {
      content = item.submit.content;
    }
    content[item.formKey] =  item.value;
    const params = {
      content,
      id: item.submit.id,
      sessionId: localStorage.getItem('sessionId')
    };
    // 请求获取新数据
    await this.http.post('application/submit', params, res => {
      // 请求数据成功 重置区域数据
      if (res.data && res.data.data) {
        item.subHtmlObj[0].data = res.data.data;
        // 切换城市重置
        if (resetArea) {
          item.subHtmlObj[0].showValue = item.subHtmlObj[0].placeHolder;
          delete item.subHtmlObj[0].value;
          // 切换城市重置具体地址
          for (let i = 0; i < this.tagData.length; i++) {
            const formItem = this.tagData[i];
            if (formItem.formType === 'detailAddress') {
              delete formItem.value;
              break;
            }
          }

        } else if (this.addressValue && this.addressValue.area) {
          //  上次的值
          item.subHtmlObj[0].value = this.addressValue.areaCode ? this.addressValue.areaCode : '';
          item.subHtmlObj[0].showValue = this.addressValue.area ? this.addressValue.area : item.placeHolder;
          this.formGroup.patchValue({ [item.subHtmlObj[0].formKey]: item.subHtmlObj[0].value });
        }

      } else {
        // 请求数据失败
        this.appGlobalService.showToast(res.message, 2000, 'middle');
      }
    });
  }

  // 获取经纬度
  getPointByCityName(obj, districtName?) {
    const that = this;
    const myGeo = new BMap.Geocoder();
    let name = '';
    if (typeof (obj) === 'object') {
      name = obj.showValue;
    } else {
      name = obj;
    }
    myGeo.getPoint((districtName !== undefined ? name + districtName : name), function (point) {
      if (point) {
        if (that.positionInfo !== null) {
          that.positionInfo.center.lng = point.lng;
          that.positionInfo.center.lat = point.lat;
        } else {
          that.positionInfo = { center: { lng: point.lng, lat: point.lat }, name: name, code: obj.value, address: name };
        }
      }
    }, name);
  }

  async openModalMapPage(item) {
    if (document.getElementById('showSelectAddressModelId').getAttribute('showAddressModal')) {
      return;
    } else {
      document.getElementById('showSelectAddressModelId').setAttribute('showAddressModal', 'true');
    }
    if (item.editable){

    } else
    if (item.disabled) {
      if (item.tips && item.tips.length > 0) {
        this.appGlobalService.showToast(item.tips, 1500, "middle");
      }

      return;
    }
    const that = this;
    // 拿到城市之后再拿城市的大区域

    if (that.addressValue && that.addressValue.area) {
      try {
        // .split(' ')[0]
        this.bigDistrict = '市' + that.addressValue.area;
      } catch (e) {
        this.bigDistrict = '';
        console.log('msg----->error=' + JSON.stringify(e));
      }
    }

    if (that.pageCity !== undefined && that.pageCityCode !== undefined) {
      item.cityName = that.pageCity + this.bigDistrict;
      item.cityCode = that.pageCityCode;
    } else {
      // 如果没有拿到pageCity则使用 存储的cityName
      item.cityName = that.positionInfo.name + this.bigDistrict;
      item.cityCode = that.positionInfo.code;
    }
    // 重新选择城市之后拿 选择之后的城市经纬度
    that.mapBaiduSerivce.getPointByName(item.cityName, async (point) => {
      const points = { lng: point.lng, lat: point.lat };
      item.longitude = points.lng;
      item.latitude = points.lat;
      item.locationValue = item.latitude.toString() + "," + item.longitude.toString();
      const modal = await this.modalCtrl.create({
        showBackdrop: true,
        component: ShowMapPage,
        componentProps: { value: item }
      });
      await modal.present();
      const { data } = await modal.onDidDismiss();
      if (data !== undefined) {
        console.log(data);
        item.value = data.value;
        item.subHtmlObj[0].value = data.location;
        item.cityName = data.cityName;
        item.cityCode = data.cityCode;
        this.addressValue.detailAddress = data.value;
        this.addressValue.location = data.location;
        this.formGroup.patchValue({ [item.formKey]: data.value, [item.subHtmlObj[0].formKey]: data.location });
      }
    });
  }
  // 选择发布类型
  chooseReleaseType(item: any, li: any) {
    if (li.check) {
      return;
    }
    item.itemList.forEach(element => {
      element.check = false;
    });
    li.check = !li.check;
    if (li.check) {
      this.formGroup.patchValue({ [item.formKey]: li.value });
    }
  }
  // 时间段选择
  currentDateFormat(date, format: string = 'HH:MM'): any {
    const pad = (n: number): string => (n < 10 ? `0${n}` : n.toString());
    return format
      .replace('yyyy', date.getFullYear())
      .replace('mm', pad(date.getMonth() + 1))
      .replace('dd', pad(date.getDate()))
      .replace('HH', pad(date.getHours()))
      .replace('MM', pad(date.getMinutes()))
      .replace('ss', pad(date.getSeconds()));
  }


  getDate(max, item) {

    if (item.max === max) {

      return item.maxDate = item.maxDate ? item.maxDate : this.getDateTime(max);
    } else if (item.min === max) {

      return item.minDate = item.mimDate ? item.minDate : this.getDateTime(max);
    }
  }

  getDateTime(date) {
    if (!date) {
      return;
    }
    if (date.indexOf(' ') > -1) {
      console.log(new Date(Date.parse(date.replace(/-/g, "/"))));
      return new Date(Date.parse(date.replace(/-/g, "/")));
    } else {
      console.log(new Date(Date.parse((date + ' ' + '23:59:59').replace(/-/g, "/"))));
      return new Date(Date.parse((date + ' ' + '23:59:59').replace(/-/g, "/")));
    }
  }

  currentValue(item) {
    if (!item.value || item.value === '') {
      item.valueN = item.placeHolder ? item.placeHolder : item.label;
    } else {
      item.valueN = item.showValue ? item.value + ' ' + ' ' + item.showValue : item.value;
    }
  }

  datetime(result: Date, item, surperItem?) {
    if(!result){
      return;
    }

    if (item.mode) {

      if (item.mode === 'year' || item.mode === 'YYYY') {
        item.value = this.currentDateFormat(result, 'yyyy');
      } else if (item.mode === 'month' || item.mode === 'YYYY MM') {
        item.value = this.currentDateFormat(result, 'yyyy-mm');
      } else if (item.mode === 'date' || item.mode === 'YYYY MM DD') {
        item.value = this.currentDateFormat(result, 'yyyy-mm-dd');
      } else if (item.mode === 'time' || item.mode === ' HH:mm') {
        item.value = this.currentDateFormat(result, 'HH:MM');
      } else if (item.mode === 'datetime' || item.mode === 'YYYY MM DD HH:mm:ss') {
        item.value = this.currentDateFormat(result, 'yyyy-mm-dd HH:MM:ss');
      } else {
        item.value = this.currentDateFormat(result, 'yyyy-mm-dd HH:MM:ss');
      }
    } else {
      item.value = this.currentDateFormat(result, 'yyyy-mm-dd HH:MM:ss');
    }
    item.showValue = item.showValue !== undefined ? this.appGlobalService.handleDate(result) : undefined;
    item.defValue = result;
    this.formGroup.patchValue({ [item.formKey]: item.value });
    if (surperItem !== undefined && surperItem.subHtmlObj && surperItem.subHtmlObj.length >= 3) {
      if (surperItem.subHtmlObj[2].formType === 'textInput' && surperItem.subHtmlObj[1].value && surperItem.subHtmlObj[0].value) {
        let iDays = Math.floor(Math.abs(surperItem.subHtmlObj[1].defValue.getTime() - surperItem.subHtmlObj[0].defValue.getTime()) / 1000 / 60 / 60 / 24);
        if (iDays < 0) {
          surperItem.subHtmlObj[2].value = 0;
          if (surperItem.lessTip && surperItem.lessTip.length > 0) {
            this.appGlobalService.showToast(surperItem.lessTip, 1500, 'middle');

          } else {
            this.appGlobalService.showToast('结束日期不能早于开通日期', 1500, 'middle');
          }
        } else {
          surperItem.subHtmlObj[2].value = iDays + 1;
        }

        this.formGroup.patchValue({ [surperItem.subHtmlObj[2].formKey]: surperItem.subHtmlObj[2].value });

      }
    } else if (surperItem.subHtmlObj[4].formType === 'textInput' && surperItem.subHtmlObj[2].value && surperItem.subHtmlObj[0].value) {
      let iDays = Math.floor((surperItem.subHtmlObj[2].defValue.getTime() - surperItem.subHtmlObj[0].defValue.getTime()) / 1000 / 60 / 60 / 24);
      if (iDays < 0) {
        surperItem.subHtmlObj[2].value = 0;
        if (surperItem.lessTip && surperItem.lessTip.length > 0) {
          this.appGlobalService.showToast(surperItem.lessTip, 1500, 'middle');

        } else {
          this.appGlobalService.showToast('结束日期不能早于开通日期', 1500, 'middle');
        }
      } else {
        surperItem.subHtmlObj[4].value = iDays + 1;
      }

      this.formGroup.patchValue({ [surperItem.subHtmlObj[4].formKey]: surperItem.subHtmlObj[4].value });

    }
  }
  ionDateChange(event, item) {
    console.log(event.detail.value);
    this.datetime(new Date(event.detail.value), item)
  }

  timeSlot(result: Date, item, index) {
    item.subHtmlObj[index].value = this.currentDateFormat(result);
    this.formGroup.patchValue({ [item.subHtmlObj[index].formKey]: item.subHtmlObj[index].value });

  }

  formatIt(date: Date, form: string) {
    const pad = (n: number) => (n < 10 ? `0${n}` : n);
    const dateStr = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
    const timeStr = `${pad(date.getHours())}:${pad(date.getMinutes())}`;
    if (form === 'YYYY-MM-DD') {
      return dateStr;
    }
    if (form === 'HH:mm') {
      return timeStr;
    }
    return `${dateStr} ${timeStr}`;
  }


  areaSlotchange(event, item, index) {
    if (event.detail.value.length > Number(item.subHtmlObj[index].maxLength)) {
      const tmpValue = event.detail.value.slice(0, Number(item.subHtmlObj[index].maxLength));
      item.subHtmlObj[index].value = tmpValue;
      this.formGroup.patchValue({ [item.subHtmlObj[index].formKey]: tmpValue });
    }

  }


  back() {
    if (this.isNextStep) {
      // 公司认证的下一步信息 合并
      // tslint:disable-next-line:forin
      for (const cons in this.formGroup.controls) {
        if (this.allForm.contains(cons)) {
          this.allForm.patchValue({ [cons]: this.formGroup.controls[cons].value });
        }
      }
      this.modalCtrl.dismiss();

    } else if (this.showSearchModal === 2) {
      if (this.formGroup.valid) {
        if (this.dataType === 1) {
          this.alert('您未提交账号信息，确定返回吗？');
        } else if (this.dataType === 0) {
          this.alert('您未提交小区信息，确定返回吗？');
        }

      } else {
        this.modalCtrl.dismiss();
      }
    } else {
      this.formGroup.reset();
      this.modalCtrl.dismiss();
    }
    if (this.modalId){
      this.pageModalService.removeModeId(this.modalId)
    }
  }

  showMessage(link) {
    if (link.type === 'modal') {
      const params = {
        pageId: link.target,
        params: link.params ? link.params : {},
        sessionId: localStorage.getItem('sessionId')
      };
      this.http.post('application/page', params, res => {
        this.pageModalService.getPageTagDataWithPageRes(
          res, data => {
            this.showRecommenMessage(data);
          }
        );
      });

    }

  }

  // 短息模板
  async showRecommenMessage(tagData) {
    const modal = await this.modalCtrl.create({
      showBackdrop: true,
      cssClass: 'recommend-modal',
      component: RecommendModalComponent,
      componentProps: { tagData },
      leaveAnimation: ModalFromCenterLeave,
      enterAnimation: ModalFromCenterEnter
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
  }



  async clickOnPickerSelect(item, event?) {
    if (item.disabled === true && item.tips && item.tips.length > 0) {
      this.appGlobalService.showToast(item.tips, 1500, "middle");
      if (event) {
      event.stopPropagation();
      }
      return
    }

    const modal = await this.modalCtrl.create({
      showBackdrop: true,
      cssClass: 'recommend-modal',
      component: FwPickerComponent,
      componentProps: { item },
      // leaveAnimation: ModalFromCenterLeave,
      // enterAnimation: ModalFromCenterEnter
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    // console.log("pickerSelect:" + JSON.stringify(modalData))
    if(modalData && modalData.data &&  modalData.data.data) {
      this.pickerSelect(modalData.data.data['result'], modalData.data.data['item']) 
    }
  }

  // 选择房型弹窗
  async openModalMultipleFormKeySelect(item, nextStep?) {
    const modal = await this.modalCtrl.create({
      showBackdrop: true,
      cssClass: "house-type",
      component: PublishHouseTypeComponent,
      componentProps: { tagData: item }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    if (modalData && modalData.data) {
      this.formGroup.patchValue({ [modalData.data.itemdata.roomType.key]: modalData.data.itemdata.roomType.value });
      this.formGroup.patchValue({ [modalData.data.itemdata.roomHall.key]: modalData.data.itemdata.roomHall.value });
      this.formGroup.patchValue({ [modalData.data.itemdata.roomBit.key]: modalData.data.itemdata.roomBit.value });
      this.houseTypeShowValue =
        modalData.data.itemdata.roomType.label +
        modalData.data.itemdata.roomHall.label +
        modalData.data.itemdata.roomBit.label;
      item.roomType = modalData.data.itemdata.roomType.value;
      item.roomHall = modalData.data.itemdata.roomHall.value;
      item.roomBit = modalData.data.itemdata.roomBit.value;
    }

  }

  ionViewDidEnter() {
    if (!this.hasSearched && this.searchBar) {
      setTimeout(() => {
        this.searchBar.setFocus();
      }, 50);
    }
  }
  
  ionBlur(item) {
    if (item.textType === 'Number' || item.textType === 'number') {
      if ( item.digit && Number(item.digit) > 0) {
        item.value = parseFloat(item.value).toFixed(Number(item.digit));
      }
    }
  }
  focusInput() {
    if (this.hasSearched) {
      this.hasSearched = false;
      this.keyword = "";
    }

  }

  search(event?) {
    if (event && event.keyCode !== 13) {
      return;
    }
    this.searchBar.getInputElement().then((input) => {
      console.log(input);
      // input.blur();
    });
    if (this.keyword === "") {
      return;
    }
    this.hasSearched = true;
    const len = this.searchArr.length;
    if (this.keyword !== "" && this.searchArr.indexOf(this.keyword) === -1) {
      this.searchArr.unshift(this.keyword);
      if (len >= 10) {
        this.searchArr.pop();
      }
      localStorage.setItem(this.searchType, JSON.stringify(this.searchArr));
    }

    this.searchKeyword(this.keyword);
  }

  searchKeyword(keyword) {
    this.keyword = keyword;
    this.hasSearched = true;
    const params = {
      content: '',
      id: '',
      sessionId: localStorage.getItem('sessionId')
    };
    let path = '';
    if (this.dataType === 1) {
      path = 'user/dataInfo' + '/' + localStorage.getItem('sessionId') + '?employee=0&mobile=' + encodeURIComponent(keyword);
    } else if (this.dataType === 2) {
      path = 'user/dataInfo' + '/' + localStorage.getItem('sessionId') + '?employee=1&mobile=' + encodeURIComponent(keyword);
    } else if (this.dataType === 0) {
      path = 'baseInfo/list/' + encodeURIComponent(keyword) + '/' + localStorage.getItem('sessionId');
    }

    this.http.get(path
      , (res: any) => {
        console.log(res);
        if (res) {
          this.sarchData = res;
        } else {
          this.sarchData = [];
        }
      });
  }

  // 输入框自动清除首尾空格 避免提交全是空格
  clearItemSpaces(event, item) {
    // 清除空格
    try {
      event.currentTarget.value = event.detail.value.replace(/^\s+|\s+$/g, '');
    } catch (error) {
      console.log('clearItemSpaces:' + JSON.stringify(error));
    }
    this.changeValue(event, item);

  }
  textAreaClearItemSpaces(event, item){
    // 清除空格
    try {
      event = event.replace(/^\s+|\s+$/g, '');
      item.value = event;
    } catch (error) {
      console.log('clearItemSpaces:' + JSON.stringify(error));
    }
    this.formGroup.patchValue({ [item.formKey]: item.value });
  }

  ionFocus(focus) {
    this.focus = focus;
  }

  searchItemClick(item) {
    if (this.dataType === 1) {

      this.formGroup.patchValue({ [Object.keys(this.formGroup.value)[0]]: item.mobile });
      this.modalCtrl.dismiss({ form: this.formGroup });

    } else if (this.dataType === 2) {

      this.formGroup.patchValue({ [Object.keys(this.formGroup.value)[0]]: item.userId });
      this.tagData.showValue = item.name + ' ' + item.mobile;
      this.tagData.value = item.userId;
      Object.assign(this.tagDataTemp, this.tagData);
      this.modalCtrl.dismiss({ form: this.formGroup });


    } else if (this.dataType === 0) {
      if (this.formGroup.contains('city_id')) {
        this.formGroup.patchValue({ city_id: item.cityCode });
        this.tagData[1].subHtmlObj[0].value = item.cityCode;

      }
      if (this.formGroup.contains('district_id')) {
        this.formGroup.patchValue({ district_id: item.areaCode });
        this.tagData[1].subHtmlObj[0].subHtmlObj[0].value = item.cityCode;
      }
      if (this.formGroup.contains('location')) {
        this.formGroup.patchValue({ location: item.location });
      }
      if (this.formGroup.contains('address')) {
        this.formGroup.patchValue({ address: item.address });
        this.tagData[1].subHtmlObj[1].value = item.address;
      }
      if (this.formGroup.contains('name')) {
        this.formGroup.patchValue({ name: item.baseName });
        this.tagData[0].value = item.baseName;
      }
      Object.assign(this.tagDataTemp, this.tagData);
      this.modalCtrl.dismiss({ form: this.formGroup, address: this.addressValue });
    }

  }

  // 户型 许可证
  async openModalLocalEdit(item) {
    const that = this;
    if (item.dataValue && typeof item.dataValue === 'string') {
      item.dataValue = JSON.parse(item.dataValue.replace(/'/g, '"'));
    }
    const modal = await this.modalCtrl.create({
      component: ModalOfLocalEditComponent,
      componentProps: { tagData: item }
    });
    modal.onDidDismiss().then(function (data) {

      that.formGroup.patchValue({ [item.formKey]: JSON.stringify(item.dataValue).replace(/\"/g, "'") });
      item.showValue = item.dataValue.length > 0 ? '编辑' : '';
    });
    return await modal.present();
  }

  tagClick(tag, it, item) {
    tag.checked = !tag.checked;
    if (typeof item.value === 'string') {
      item.value = item.value.split(',');
      if (item.value.indexOf('') > -1) {
        item.value.splice(item.value.indexOf(''), 1);
      }

    }
    // 没有第三级
    if (tag === it) {
      if (tag.checked) {
        item.current.hasValue = true;

      } else {
        let hasValue = false;
        item.current.children.forEach(element => {
          if (element.checked) {
            hasValue = true;
          }
        });
        item.current.hasValue = hasValue;
      }
    } else {
      let i = 0;
      it.children.forEach(element => {
        element.checked ? ++i : '';
      });
      (i === it.children.length && i > 0) ? it.checked = true : it.checked = false;
      if (it.checked) {
        if (item.current) {
          item.current.hasValue = true;
        }

        // 加入大类 清除小类
        item.value.push(it.value);
        it.children.forEach(element => {

          const index = item.value.findIndex(v => (v === element.value));
          if (index > -1) {
            item.value.splice(index, 1);
          }

        });
      } else {
        it.children.forEach(element => {
          // 先清除
          if (item.current) {
            item.current.hasValue = false;
          }
          if (item.value) {
            const index = item.value.findIndex(v => (v === element.value || v === it.value));
            if (index > -1) {
              item.value.splice(index, 1);
            }
          }


        });

        // 再加入
        it.children.forEach(element => {
          if (element.checked) {
            if (item.current) {
              item.current.hasValue = true;
            }
            item.value.push(element.value);
          }
        });
      }
    }

    this.checkBigVaue(item);
    console.log(item.value);
    this.formGroup.patchValue({ [item.formKey]: item.value })

  }
  level3Click(level3,item) {
    level3.checked = !level3.checked;
    if (typeof item.value === 'string') {
      item.value = item.value.split(',');
      if (item.value.indexOf('') > -1) {
        item.value.splice(item.value.indexOf(''), 1);
      }

    }
    {
      let i = 0;
      item.current.current.children.forEach(element => {
        element.checked ? ++i : '';
      });
      (i === item.current.current.children.length && i > 0) ? item.current.current.checked = true : item.current.current.checked = false;
      if (item.current.current.checked) {
        if (item.current.current) {
          item.current.current.hasValue = true;
        }

        // 加入大类 清除小类
        item.value.push(item.current.current.value);
        item.current.current.children.forEach(element => {

          const index = item.value.findIndex(v => (v === element.value));
          if (index > -1) {
            item.value.splice(index, 1);
          }

        });
      } else {
        item.current.current.children.forEach(element => {
          // 先清除
          if (item.current.current) {
            item.current.current.hasValue = false;
          }
          if (item.value) {
            const index = item.value.findIndex(v => (v === element.value || v === item.current.current.value));
            if (index > -1) {
              item.value.splice(index, 1);
            }
          }


        });

        // 再加入
        item.current.current.children.forEach(element => {
          if (element.checked) {
            if (item.current.current) {
              item.current.current.hasValue = true;
            }
            item.value.push(element.value);
          }
        });
      }
    }
    this.checkBigVaue(item);
    console.log(item.value);
    this.formGroup.patchValue({ [item.formKey]: item.value })
  }

  checkAllL1(event,level1,item){
   if (item.current !== level1) {
    this.itemLeftClick(level1,item);
   }
   this.chooseCurrentAll(item)  
   event.stopPropagation();
  }
  itemCenterClick(level2,item){
    item.current.current.open = false;
    item.current.current = level2;
    level2.open = true;
  }
  checkAllL2(event,level2,item){

    if (item.current.current !== level2) {
      item.current.current.open = false;
      item.current.current = level2; // 3
      level2.open = true;
     }
     this.chooseCurrentL2All(item);
    event.stopPropagation();
  }

  chooseCurrentL2All(item) {
    item.current.current.checked = !item.current.current.checked;
    if (item.current.current.checked) {
      item.current.current.hasValue = true;
      item.current.current.children.forEach(element => {
        element.checked = true;
      });
    } else {
      item.current.current.hasValue = false;
      item.current.current.children.forEach(element => {
        element.checked = false;
      });
    }
    this.checkBigVaue(item);
    console.log(item.value);
    this.formGroup.patchValue({ [item.formKey]: item.value })
  }

  chooseCurrentAll(item) {
    item.current.checked = !item.current.checked;
    if (item.current.checked) {
      item.current.hasValue = true;
      item.current.children.forEach(element => {
        element.checked = true;
        element.hasValue = true;
        element.children.forEach(e => {
          e.checked = true;

        });
      });
    } else {
      item.current.hasValue = false;
      item.current.children.forEach(element => {
        element.checked = false;
        element.hasValue = false;
        element.children.forEach(e => {
          e.checked = false;

        });
      });
    }
    this.checkBigVaue(item);
    console.log(item.value);
    this.formGroup.patchValue({ [item.formKey]: item.value })
  }
  openOrCloseClick(it) {
    it.open = !it.open;
  }
  chooseAll(it, item) {
    it.checked = !it.checked;

    if (it.checked) {
      if (item.current) {
        item.current.hasValue = true;
      }

      if (typeof item.value === 'string') {
        item.value = item.value.split(',');
      }
      item.value.push(it.value);
      // 加入大类 清除小类
      it.children.forEach(element => {
        element.checked = true;
        const index = item.value.findIndex(v => (v === element.value));
        if (index > -1) {
          item.value.splice(index, 1);
        }
      });

      // this.checkBigVaue(item);
    } else {
      if (item.current) {
        item.current.hasValue = false;
      }
      it.children.forEach(element => {
        element.checked = false;
        //  清除 大类、小类
        const index = item.value.findIndex(v => (v === element.value) || it.value === v);
        if (index > -1) {
          item.value.splice(index, 1);
        }
      });

    }
    this.checkBigVaue(item);
    console.log(item.value);
    $('#' + it.value).slideToggle("slow");
    this.formGroup.patchValue({ [item.formKey]: item.value })

  }
  // 单选左边大类点击
  singleItemLeftClick(it, item) {
    item.children.forEach(element => {
      element.open = false;
    });
    it.open = true;
    item.current = it;
  }
  // 单选
  singleTagClick(tag, item) {
    if (item.currentTag) {
      item.currentTag.checked = false;
    }
    
    item.current.children.forEach(element => {
      element.checked = false;
      if (element.children)
      element.children.forEach(el => {
        el.checked = false;
      });
    });

    tag.checked = true;
    item.currentTag = tag;
    item.value = tag.value;
    item.showValue = tag.label;
    Object.assign(this.tagDataTemp, this.tagData);
    this.formGroup.patchValue({ [item.formKey]: item.value });
    this.modalCtrl.dismiss({ form: this.formGroup });

  }
  // 左边大类点击
  itemLeftClick(it, item) {
    item.current.open = false;
    if (item.current.children && item.current.children[0].open) {
      item.current.children[0].open = false;
    }
    
    it.open = true;
    item.current = it;
    
    if (item.formType === 'threeLevelSelection' && item.current.children &&  item.current.children[0]) {
      item.current.current = item.current.children[0]; // 3
      item.current.children[0].open = true;
    }
  }

  checkBigVaue(item) {
    // 遍历当前二级分类是否全选
    if (item.current) {
      let n = 0;
      item.current.children.forEach(element => {
        element.checked ? ++n : '';
      });
      // 全选择 清除 二三级
      if (item.current.children.length === n) {
        item.current.checked = true;
        const index = item.value.findIndex(v => (v === item.current.value));
        if (index == -1) {
          item.value.push(item.current.value);    
        }
        // 清除 二级
        item.current.children.forEach(element => {

          const index = item.value.findIndex(v => (v === element.value));
          if (index > -1) {
            item.value.splice(index, 1);
          }
          // 清除 三级
          this.removeValue(item, element);
        });
      } else {
        item.current.checked = false;
        item.current.hasValue = false;
        // 清除一级分类value
        const index = item.value.findIndex(v => (v === item.current.value));
        if (index > -1) {
          item.value.splice(index, 1);
        }
        // 遍历 二 三级
        item.current.children.forEach(element => {
          if (element.checked) {
            item.current.hasValue = true;
            if (item.value.findIndex(v => (v === element.value)) === -1) {
              item.value.push(element.value);
            }

          } else {
            if (item.value.findIndex(v => (v === element.value)) > -1) {
              item.value.splice(item.value.findIndex(v => (v === element.value), 1));
            }
            element.children.forEach(e => {
              if (e.checked) {
                item.current.hasValue = true;
                if (item.value.findIndex(v => (v === e.value)) === -1) {

                  item.value.push(e.value);
                }
              }
            });
          }

        });
      }
    }
  }

  removeValue(item, it) {
    it.children.forEach(e => {
      const index = item.value.findIndex(v => (v === e.value));
      if (index > -1) {
        item.value.splice(index, 1);

      }
    });
  }
  addValue(item, it) {
    it.children.forEach(e => {
      if (e.checked && item.value.findIndex(v => (v === e.value)) === -1) {
        item.value.push(e.value);
      }
    });
  }

  // 服务类型
  async showAllType(tagData) {
    const modal = await this.modalCtrl.create({
      showBackdrop: true,
      component: ServiceTypeComponent,
      componentProps: { tagData }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
  }
  // 评分
  updateRateReturn(event, item) {
    item.data.forEach(element => {
      if (parseInt(element.value,10)  === event) {
        item.showValue = element.label;
      }
    });
    this.formGroup.patchValue({ [item.formKey]: event });

  }

  getMSCode(item, it) {

    if (this.formGroup.get([item.formKey]).errors) {
      this.appGlobalService.showToast('请输入正确手机号码', 2000, 'top');
    } else {
      if (it.submit) {
        const params = {
          content: { [item.formKey]: item.value },
          id: it.submit.id,
          sessionId: localStorage.getItem('sessionId')
        };
        this.http.post('application/submit', params, res => {
          if (res.success && res.data.result) {
            this.time = 90;
            const timer = setInterval(() => {
              this.time = this.time - 1;
              if (this.time === -1) {
                clearInterval(timer);
              }
            }, 1000);

            if (res.data.result.code) {
              it.value = res.data.result.code;
              this.formGroup.patchValue({ [it.formKey]: it.value });

            }
          }
          if (res.message && res.message.length > 0) {
            this.appGlobalService.showToast(res.message, 1500, 'top');
          }

        });
      }
    }

  }

  passWordIonBlur(item) {
    item.onFocus = false;
  }
  passWordIonFocus(item) {
    item.onFocus = true;
  }
  switchButtonSystem(item) {

    item.value = item.showValue ? '1' : '0';
    this.formGroup.patchValue({ [item.formKey]: item.value });
    this.checkSubHtmlObj(item);
  }

  nextPage(item) {
    if (this.formGroup.valid) {
      // 表示当前不是最后一步页面,不显示提交btn
      this.openModalMoreEditInfo(item, '', item.showValue === 'NoShowSubmit' ? false : true);
    } else {
      this.getErrors(this.formGroup);
    }

  }
  async modalMultipleSelect3FullScreen(item, auto?) {
    if (!item.children || item.children.length === 0) {
      if (item.tips && item.tips.length > 0) {
        this.appGlobalService.showToast(item.tips, 1500, "middle");
      }
      return;
    }
    const that = this;
    if (auto) {
      item.auto = auto;
    }
    const modal = await this.modalCtrl.create({
      component: ModalMultipleSelect3FullScreenComponent,
      componentProps: { value: item },

    });
    modal.onDidDismiss().then(function (data) {
      // that.formGroup.patchValue({ [item.formKey]: item.value });
      if (data.data) {
        const selectedData = data.data;
        const selectedLabel = selectedData.map(v => {
          return v.label;
        });
        const selectedValue = selectedData.map(v => {
          return v.value;
        });
        if (data.data.length) {
          that.formGroup.patchValue({ [item.formKey]: selectedValue });
          item.value = selectedValue;
          item.showValue = selectedLabel;
        } else {
          that.formGroup.patchValue({ [item.formKey]: '' });
          item.value = '';
        }
      }
    });
    return await modal.present();
  }
  async modalMultipleSelect3(item, auto?) {
    if (!item.children || item.children.length === 0) {
      if (item.tips && item.tips.length > 0) {
        this.appGlobalService.showToast(item.tips, 1500, "middle");
      }
      return;
    }
    const that = this;
    if (auto) {
      item.auto = auto;
    }
    const id = that.pageModalService.addModeId()
    const modal = await this.modalCtrl.create({
      component: ModalMultipleSelect3Component,
      componentProps: { value: item },
      cssClass: 'auto-modal',
      id:id
    });
    modal.onDidDismiss().then(function (data) {
      that.pageModalService.removeModeId(id)
      that.formGroup.patchValue({ [item.formKey]: item.value });
      if (data.data) {
        const selectedData = data.data;
        const selectedLabel = selectedData.map(v => {
          return v.label;
        });
        const selectedValue = selectedData.map(v => {
          return v.code;
        });
        if (data.data.length) {
          that.formGroup.patchValue({ [item.formKey]: selectedValue });
          item.value = selectedValue;
          item.showValue = selectedLabel;
        } else {
          that.formGroup.patchValue({ [item.formKey]: '' });
          item.value = '';
        }
      }
    });
    return await modal.present();
  }

  endIconClick(item) {
    if (item.endIcon === 'release_icon_contact@3x.png' && item.subHtmlObj && item.subHtmlObj.length === 1 && item.subHtmlObj[0].formType.indexOf('textInput') > -1) {
      this.contacts.pickContact().then((contact) => {
        console.log("contacts:-->" + JSON.stringify(contact));
        //this.familyDisplayName = contact.displayName; 
        //更新： Android的全名显示在displayName，IOS的全名显示在name.formatted
        const name = contact.displayName != null ? contact.displayName : contact.name.formatted;
        const familyPhoneNumbers = contact.phoneNumbers;

        item.value = name;
        this.formGroup.patchValue({ [item.formKey]: name })

        const that = this;
        const buttons: any = [];
        familyPhoneNumbers.forEach(element => {

          element.value = element.value.replace(/\s|[(]|[)]|[（]|[）]|[-]*/g, '');

          var regx = /(1[3|4|5|6|7|8|9][\d]{9})/g;
          var phoneNums = element.value.match(regx);

          if (phoneNums && phoneNums.length > 0) {
            element.value = phoneNums[0]
            buttons.push(phoneNums[0]);
          }
        });

        if (buttons.length > 1) {
          ActionSheetService.showActionSheetWithOptions(
            {
              title: '请选择号码',
              options: buttons,
              maskClosable: true
            },
            buttonIndex => {
              if (buttonIndex > -1) {
                console.log(buttons[buttonIndex]);
                item.subHtmlObj[0].value = buttons[buttonIndex];
                this.formGroup.patchValue({ [item.subHtmlObj[0].formKey]: buttons[buttonIndex] })
              }
            }
          );
        } else if (buttons.length === 1) {
          item.subHtmlObj[0].value = buttons[0];
          this.formGroup.patchValue({ [item.subHtmlObj[0].formKey]: buttons[0] })
        } else {
          console.log("该联系人 无手机号码");
          item.subHtmlObj[0].value = '';
          this.formGroup.patchValue({ [item.subHtmlObj[0].formKey]: '' })
        }
      });
    }


  }
  designStyle(itemInfo, item) {
    // 不可以选
    if (itemInfo.status !== 'true') {
      return;
    }
    itemInfo.check = !itemInfo.check;
    if (!item.checkArray) {
      item.checkArray = [];
    }
    if (itemInfo.check) {
      item.checkArray.push(itemInfo);
    } else {
      let index = item.checkArray.indexOf(itemInfo);
      if (index > -1) {
        item.checkArray.splice(index, 1);
      }
    }


    let i = 0;
    let value = '';
    let valueArray: any = [];
    let showValueArray: any = [];
    item.checkArray.forEach(element => {
      if (element.check) {
        element.index = ++i;
        valueArray.push(element.value)
        showValueArray.push(element.label)
      }
    });
    value = valueArray.join(',');
    if (item.sep !== undefined) {
      value = valueArray.join(item.sep);
    }
    item.value = value;
    item.showValue = showValueArray.join(',');
    this.formGroup.patchValue({ [item.formKey]: item.value });

  }

  
  // 数组btn
  iconButtonClick(item) {

    this.eventService.eventEmit.emit("searchType100", item);
  }

  closeHint(event) {
    event.stopPropagation();
    $('#' + this.hintId).fadeOut();
  }
  ngOnDestroy(): void {
    this.nextPageFomObj = undefined;
    clearInterval(this.timer);
    clearInterval(this.timer1);    
    if ((typeof Keyboard) !== 'undefined' && localStorage.getItem('client') === 'APP') {
      Keyboard.disableScroll(true);
      Keyboard.setResizeMode('native');
      console.log('iOS:Keyboard.disableScroll!!!!' );
    }

  }

  onCancelClick(e) {
    e.stopPropagation();
  }
  dismissClick() {
    this.modalCtrl.dismiss();
  }
  //生成日期
  createDate(item) {
    let weeks = ['日', '一', '二', '三', '四', '五', '六']
    let month;
    let day;
    let y;
    let week;
    let res;
    let res_;
    //现在的时间
    let startDate = new Date();
    if(item.minSize && item.minSize > 0) {
      startDate.setDate(startDate.getDate() + Number(item.minSize));
    }
    let now_day = new Date().getDate();
    let m = `0${startDate.getMonth() + 1}`;
    //未来的时间
    let endDate = new Date();
    endDate.setDate(startDate.getDate() + item.maxSize)

    while ((endDate.getTime() - startDate.getTime()) > 0) {

      //月、日是否需要拼接0
      month = (startDate.getMonth() + 1).toString().length === 1 ? "0" + (startDate.getMonth() + 1).toString() : (startDate.getMonth() + 1);
      day = startDate.getDate().toString().length === 1 ? "0" + startDate.getDate() : startDate.getDate();
      y = startDate.getFullYear()
      //是否拼接‘周’
      if ((day - now_day) === 0 && month === m) {
        week = '今天'
      } else if ((day - now_day) === 1 && month === m) {
        week = '明天'
      } else if ((day - now_day) === 2 && month === m) {
        week = '后天'
      } else {
        week = '周' + weeks[startDate.getDay()]
      }
      res = month + '月' + day + '日' + `(${week})`
      res_ = `${y}-${month}-${day}`

      item.daysList.push({ label: res, value: res_, check: false , week})

      //天数加+1
      startDate.setDate(startDate.getDate() + 1)
    }
    item.daysList[0].check = true
  }
  //生成时分 具体时间
  createHour(item) {
    let hour;
    let hour_;
    let mm;
    let mm_;
    let time = 8;
    let endTime = 22 - (item.unit ? Number(item.unit) - 1 : 0)
    while (time < endTime) {

      hour = `${time}:00`
      mm = `${time}:30`

      if (time < 10) {
        hour_ = `0${time}:00`
        mm_ = `0${time}:30`
      } else {
        hour_ = `${time}:00`
        mm_ = `${time}:30`
      }

      item.itemList.push({ label: hour, value: hour_, check: false })
      item.itemList.push({ label: mm, value: mm_, check: false })

      time++
    }
    //去除最后的半小时
    item.itemList.splice(-1, 1)
    item.itemList[0].check = true
  }

  //生成时分 时间范围
  createHourRange(item) {
    let hour;
    let hour_;
    let time = 9;
    let apn;
    let maxTime = item.max ? item.max : 22;
    let sep ; // 生成时间间隔 如 09:00 - 10:00
    this.min = item.min ? item.min : 1; // 分钟  ’现在时‘减去‘生成的最大时’ 要大于 min
    if (item.sep) {
      sep = item.sep;
    } else {
      sep = item.sep = 1;
    }
    sep = Number(sep);
    if (item.extra && item.extra === '1') {
      while (time < maxTime) {
        hour = `${time}:00-${time + sep}`

        if (time < 10) {
          hour_ = `0${time}:00-${time + sep}:00`
        } else {
          hour_ = `${time}:00-${time + sep}:00`
        }

        if (time == 9) {
          apn = '上午'
          item.itemList.push({ label: hour, value: hour_, check: false, apn: apn })
        } else if (time == 12) {
          apn = '下午'
          item.itemList.push({ label: hour, value: hour_, check: false, apn: apn })
        } else if (time == 18) {
          apn = '晚上'
          item.itemList.push({ label: hour, value: hour_, check: false, apn: apn })
        } else {
          item.itemList.push({ label: hour, value: hour_, check: false })
        }
        time = time + sep;

      }
    } else {
      while (time < maxTime) {
        hour = `${time}:00-${time + sep}`

        if (time < 10) {
          hour_ = `0${time}:00-${time + sep}:00`
        } else {
          hour_ = `${time}:00-${time + sep}:00`
        }
        item.itemList.push({ label: hour, value: hour_, check: false });
        time = time + sep;

      }
    }
    let value: any;
    let index_: any;
    let showToday = false;

    try {
      item.itemList.forEach((e, index) => {
        if (e.value.slice(6,8)*60 - (this.todayHHMM.slice(0,2)*60 + (this.todayHHMM.slice(3,5) - 0) + sep*60) >= this.min) {
          value = item.daysList[0].value + ' ' + e.value;   // 时间格式 2022-05-05 08:00-09:00
          item.showValue = item.daysList[0].label + ' ' + e.value; // 展示格式 2022-05-05(明天) 08:00-09:00
          this.formGroup.patchValue({ [item.formKey]: value});   // 默认选中项
          item.itemList[index].check = true;
          index_ = index;
          showToday = true
          throw new Error();
        } else {
          e.isShow = false;
        }
      });
    } catch (error) {
      
    }

    if (!showToday){
      item.daysList[0].isHidden = 'true';
    }

    // 快递100 处理成三个字段 2022-05-05 08:00-09:00
    if (item.formKeys && item.formKeys.indexOf(";") > -1 && item.itemList[0].value && item.itemList[0].value.indexOf("-") > -1) {

      const keyArray = item.formKeys.split(";");
      if (this.formGroup.contains(keyArray[0])) {
        this.formGroup.patchValue({ [keyArray[0]]: item.itemList[0].value.split("-")[0]});
        this.formGroup.patchValue({ [keyArray[1]]: item.itemList[0].value.split("-")[1] });        
        if (value) {
          this.formGroup.patchValue({ [keyArray[0]]: item.itemList[index_].value.split("-")[0]});
          this.formGroup.patchValue({ [keyArray[1]]: item.itemList[index_].value.split("-")[1]});
        }
      } else {
        this.formGroup.addControl(keyArray[0], new FormControl(item.itemList[0].value.split("-")[0]));
        this.formGroup.addControl(keyArray[1], new FormControl(item.itemList[0].value.split("-")[1]));
      }

      if (value) {
        item.value = item.daysList[0].week; // 使用今天、明天、后天
        item.showValue = item.daysList[0].week + ' ' + item.itemList[index_].value;
        this.formGroup.patchValue({ [item.formKey]: item.value });
      } else {
        // 说明’今天‘没有可选时间，则展示’明天‘
        this.heightLightLeft(item, item.daysList[1], 1);
        item.daysList[0].isHidden = 'false';
      }

    }

  }

  heightLightLeft(item, ite, i?) {
    if (ite.check != true) {
      //高亮显示
      item.daysList.forEach(e => {
        e.check = false
      })
      ite.check = true
      //右边重选
      item.itemList.forEach(e => {
        if (e.check === true) {
         e.check = false
        }
      });

      if (i === 0 && item.formType === "chooseTimeRange") {
        let value: any;
        try {
          item.itemList.forEach((e, index) => {
            if ((e.value.slice(6,8)*60) - (this.todayHHMM.slice(0,2)*60 + (this.todayHHMM.slice(3,5) - 0) + item.sep*60) >= this.min) {
              value = item.daysList[0].value + ' ' + e.value; // 时间格式 2022-05-05 08:00-09:00
              item.showValue = item.daysList[0].label + ' ' + e.value; // 展示格式 2022-05-05(明天) 08:00-09:00
              this.formGroup.patchValue({ [item.formKey]: value});   
              item.itemList[index].check = true; // 默认选中项
              // if (value && item.formKeys && item.formKeys.indexOf(";") > -1 && item.itemList[0].value && item.itemList[0].value.indexOf("-") > -1) {        
              //   item.value = item.daysList[0].week; // 使用今天、明天、后天
              //   item.showValue = item.daysList[0].week + ' ' + item.itemList[index].value;
              //   this.formGroup.patchValue({ [item.formKey]: item.value });
              // }
              this.heightLightRight(item, item.itemList[index])

              throw new Error();
            }
          });
        } catch (error) {
          
        }
      } else if (i !== 0 && item.formType === "chooseTimeRange") {
        item.itemList[0].check = true;
        let value = ite.value + ' ' + item.itemList[0].value;
        item.showValue = ite.label + ' ' + ite.value;
        this.formGroup.patchValue({ [item.formKey]: value});   // 默认选中项

        // if (item.formKeys && item.formKeys.indexOf(";") > -1 && item.itemList[0].value && item.itemList[0].value.indexOf("-") > -1) {                  
        //   item.value = ite.week // 使用今天、明天、后天
        //   item.showValue = ite.week + ' ' + item.itemList[0].value;
        //   this.formGroup.patchValue({ [item.formKey]: item.value });
        // }
        this.heightLightRight(item, item.itemList[0])
      }
    }
  }

  heightLightRight(item, ite) {
    // if (ite.check != true) {

      item.itemList.forEach(e => {
        e.check = false
      })
      ite.check = true

      let dateStr = '';
      let week = '';
      let hourStr = '';
      item.daysList.forEach(e => {
        if (e.check == true) {
          dateStr = e.value
          week = e.week
        }
      })
      hourStr = ite.value
      item.value = dateStr + ' ' + hourStr
      item.showValue = item.value;
      this.formGroup.patchValue({ [item.formKey]: item.value });

    // 快递100 处理成三个字段 2022-05-05 08:00-09:00
    if (item.formKeys && item.formKeys.indexOf(";") > -1 && hourStr && hourStr.indexOf("-") > -1) {

      const keyArray = item.formKeys.split(";");
      if (this.formGroup.contains(keyArray[0])) {
        this.formGroup.patchValue({ [keyArray[0]]: hourStr.split("-")[0]});
        this.formGroup.patchValue({ [keyArray[1]]: hourStr.split("-")[1] });
      } else {
        this.formGroup.addControl(keyArray[0], new FormControl(hourStr.split("-")[0]));
        this.formGroup.addControl(keyArray[1], new FormControl(hourStr.split("-")[1]));
      }
      item.value = week; // 使用今天、明天、后天
      item.showValue = week + ' ' + hourStr;
      this.formGroup.patchValue({ [item.formKey]: item.value });
    }

    // }
  }

  // 更新行业数据
  submitAction(event, item) {

    if (event) {
      const selectedData = event;
      const selectedLabel = selectedData.map(v => {
        return v.label;
      });
      const selectedValue = selectedData.map(v => {
        return v.value;
      });
      if (event.length) {
        this.formGroup.patchValue({ [item.formKey]: selectedValue });
        item.value = selectedValue;
        item.showValue = selectedLabel;
      } else {
        this.formGroup.patchValue({ [item.formKey]: '' });
        item.value = '';
      }
    }
    Object.assign(this.tagDataTemp, this.tagData);
    this.modalCtrl.dismiss({ form: this.formGroup });
  }

  //本地搜索品牌
  searchLocal(event, item) {
    if (event && event.keyCode !== 13) {
      return;
    }
    this.searchBarLocal.getInputElement().then((input) => {
      item.keyword = input.value;
      item.keyword = item.keyword.trim();
      if (item.keyword === "") {
        return;
      }

      this.searchKeywordLocal(item);

    });


  }
  searchKeywordLocal(item) {
    if (!item.keyword || item.keyword === "") {
      item.hasSearched = false;
      item.itemList = item.tempList;
      return;
    }
    item.hasSearched = true;
    item.searchResult = [];

    for (var i = 0; i < item.tempList.length; i++) {
      var num = i;
      for (var j = 0; j < item.tempList[num].label.length; j++) {
        var Name1 = item.tempList[num].label.charAt(j);
        for (var k = 0; k < item.keyword.length; k++) {
          var Name2 = item.keyword.charAt(k);
          if (Name1.toUpperCase() == Name2.toUpperCase()) {
            if (item.searchResult.indexOf(item.tempList[num]) < 0) {
              // 如果有相同的字，且不在数组内，加入数组。
              item.searchResult.push(item.tempList[num]);
            }
          }
        }
      }
    }

    item.itemList = item.searchResult;
  }

  ionBlurLocal() {
  }

  focusInputLocal(item) {
    if (item.tempList === undefined) {
      item.tempList = item.itemList;
    }
    if (item.hasSearched) {
      item.hasSearched = false;
      item.keyword = "";
    }
  }

  searchChangeLocal(event, item) {
    this.searchKeywordLocal(item);
  }

  checkStatus(item, a){
    let status = false;
    if (item.value === item.itemList[a].value  || 
      item.value.split(',').indexOf(item.itemList[a].value) > -1 || 
      item.value.split(';').indexOf(item.itemList[a].value) > -1) {
      status = true; 
    } 
    return  status
  }
  typeChangeValue(event, item){
    if (item.subHtmlObj && item.subHtmlObj[0].formType === 'addType') {
      if (event.detail.value.length > Number(item.subHtmlObj[0].maxLength)) {
        item.subHtmlObj[0].value = event.detail.value.slice(0, Number(item.subHtmlObj[0].maxLength));
        this.formGroup.patchValue({ [item.subHtmlObj[0].formKey]: item.subHtmlObj[0].value });
      } else {
        item.subHtmlObj[0].value = event.detail.value; 
      }
    }
  }
  typeCheckClick(item){
    if (item.subHtmlObj[0].value){  
      if(item.subHtmlObj && item.subHtmlObj[0].butSubmit){
        item.subHtmlObj[0].butSubmit.content[item.subHtmlObj[0].formKey] = item.subHtmlObj[0].value
        const params = {
          content: item.subHtmlObj[0].butSubmit.content,
          id: item.subHtmlObj[0].butSubmit.id,
          sessionId: localStorage.getItem('sessionId')
        };
        this.http.post('application/submit', params, res => {
          if (res.success && res.data && res.data.eventResult) {
  
            item.itemList.forEach(element => {
              element.check = false;
            })
            item.value = res.data.eventResult;
            item.showValue = item.subHtmlObj[0].value;
            item.itemList.push({label:item.subHtmlObj[0].value,value:res.data.eventResult,check:true})
            item.subHtmlObj[0].value = ''
            item.subHtmlObj[0].check = false;
            this.formGroup.patchValue({[item.formKey]:item.value})
          }
  
        });
  
      }
    } else {
      if (item.subHtmlObj[0].tips) {
        this.appGlobalService.showToast(item.subHtmlObj[0].tips,1500,"top")
      } else {
        this.appGlobalService.showToast('请输入分类名称',1500,"top")
      }
    }
  
  }

  setItemDefValue(item) {

    if (item.defValue) {
      item.value = item.defValue;
      this.formGroup.patchValue({ [item.formKey]: item.defValue });

    }
  }
  closeTips(tipId, listId) {
    const tempButton = document.getElementById(tipId) as HTMLElement;
    $('#' + tipId).slideToggle("slow");
    document.getElementById(listId).setAttribute('style', 'height:100%;');

  }
  pickerSelectTwo(result, item, type?) {
    if (result && result.length && Array.isArray(result)) {
      if (type === 1) {
        item.showValue1 = result[0].label + result[1].label;
        item.value1 = result[0].label + result[1].label;
        JSON.parse(item.data2).forEach(element => {
          element.children.forEach(e => {
            if (e.value === result[1].value) {
              item.data2 = e.children;
              item.disabled2 = false;
              item.showValue = "具体位置";
            }
          });
        });
      } else {
        item.showValue = result[0].label;
        item.value = result[0].value;
        this.formGroup.patchValue({ [item.formKey]: item.value });
      }
    }
  }

  paresAddress( item) {

    const [result] = AddressParse.parse(item.value,true);
    console.log(result);
    if(result){
      this.tagData.forEach(element => {
        this.showAddress(item,result,element);     
        if (element.subHtmlObj !== undefined && element.subHtmlObj.length > 0) {
          element.subHtmlObj.forEach(e => {
            this.showAddress(item,result,e);
            if (e.subHtmlObj !== undefined && e.subHtmlObj.length > 0) {
              e.subHtmlObj.forEach(e3 => {
                this.showAddress(item,result,e3);
              });
            }
          });
          
          
        }
      })
    }
    
    
  }

 showAddress(item,result,element){
  item.itemList.forEach(ele => {
    if (ele.value && element.formKey &&  element.formKey === ele.value){
        element.value = result[ele.label];
        this.formGroup.patchValue({[element.formKey]:element.value})
        if (ele.label === 'code'){
          if (item.maxSize === 1) {
            element.showValue = result.area  
          } else {
            element.showValue = result.city+result.area
          }
          
        }
        // 快递100 特殊处理拼接全地址
        if (ele.label === 'details' && ele.value.indexOf('ManPrintAddr')> -1) {
          if (result.province) {
            element.value =  result.province;
          }
          if (result.city) {
            element.value +=  result.city;
          }
          if (result.area) {
            element.value +=  result.area;
          }
          if (result.details) {
            element.value +=  result.details;
          }
        }
    }

  });
 }
  
  outputTextInput(event){
    if(event.fun){
      switch (event.fun) {
        case 'inputClick':
          this.inputClick(event.item);  
          break;
        case 'endIconClick':
          this.endIconClick(event.item);  
          break;
          case 'deleteValue':
        this.deleteValue(event.item);  
        break;
        case 'showActionSheet':
        this.showActionSheet(event.item);  
        break;
        case 'errorChecked':
        // this.errorChecked(event.item);  
        break;
        case 'changeValue':
        this.changeValue(event.event ,event.item);  
        break;
        case 'getMSCode':
        this.getMSCode(event.superitem,event.item);  
        break;
        case 'getServicePrice':
        // this.getServicePrice(event.item,event.tag);  
        break;
        case 'ionBlur':
        this.ionBlur(event.item);  
        
        break;
        // textArea
        case 'clearItemSpaces':
          this.clearItemSpaces(event.event,event.item);  
          break;
        case 'textAreaClearItemSpaces':
        this.textAreaClearItemSpaces(event.event, event.item);
        break;
        case 'setItemDefValue':
          this.setItemDefValue(event.item);  
          break;
          
        //switchButton
        case 'changeItemobjValidator':
          this.changeItemobjValidator(event.item,event.formType,event.i);
          break;
          
        case 'openPage': {
            this.openPage(event.link);
          }
          break;
        case 'switchButtonSystem':
          this.switchButtonSystem(event.item);
          break;

        case 'closeTips':
          this.closeTips(event.tipId, event.listId);
          break;

        case 'focusInputLocal':
          this.focusInputLocal(event.item);
          break;
        case 'searchLocal':
          this.searchLocal(event.event, event.item);
          break;
        case 'searchChangeLocal':
            this.searchChangeLocal( event.event,event.item);
            break;
        // passwordType
        case 'passWordIonBlur':
          this.passWordIonBlur(event.item);
          break;
        case 'passWordIonFocus':
            this.passWordIonFocus(event.item);
            break;      
             // passwordType
        case 'passWordIonBlur':
          this.passWordIonBlur(event.item);
      break;
        case 'passWordIonFocus':
                this.passWordIonFocus(event.item);
          break;        
        // PickerSelect
        case 'clickOnPickerSelect':
          this.clickOnPickerSelect(event.item);
          break;     
        case 'pickerSelect':
            this.pickerSelect( event.event,event.item);
          break;      
        case 'pickerSelectTwo':
            this.pickerSelectTwo( event.event,event.item);
          break;      
        // date
        case 'getDate':
          this.getDate(event.maxOrMin, event.item);
          break;
        case 'timeSlot':{
          this.timeSlot(event.event, event.item, event.i);
        }
          break;  
        case 'datetime':
          {
            this.datetime(event.event, event.item);
            this.currentValue( event.item);
          }
          break;
        case 'ionDateChange':
          
          {
            this.ionDateChange(event.event, event.item);
            this.currentValue( event.item);
          }          
          break;
        case 'currentValue':  
        this.currentValue( event.item);
        break;
        case 'paresAddress':  
        this.paresAddress( event.item);
        break;
        // case 'changeAddress':  
        // this.changeAddress( event.item);
        // break;
        default:
          break;
      }
      
    }
  }
}
